github.com/nakabonne/golangci-lint@v1.26.1/README.md (about) 1 # GolangCI-Lint 2 3 [![Build Status](https://travis-ci.com/golangci/golangci-lint.svg?branch=master)](https://travis-ci.com/golangci/golangci-lint) 4 [![GolangCI](https://golangci.com/badges/github.com/golangci/golangci-lint.svg)](https://golangci.com) 5 [![License](https://img.shields.io/github/license/golangci/golangci-lint)](/LICENSE) 6 [![Release](https://img.shields.io/github/release/golangci/golangci-lint.svg)](https://github.com/golangci/golangci-lint/releases/latest) 7 [![Docker](https://img.shields.io/docker/pulls/golangci/golangci-lint)](https://hub.docker.com/r/golangci/golangci-lint) 8 9 GolangCI-Lint is a linters aggregator. It's fast: on average [5 times faster](#performance) than gometalinter. 10 It's [easy to integrate and use](#command-line-options), has [nice output](#quick-start) and has a minimum number of false positives. It supports go modules. 11 12 GolangCI-Lint has [integrations](#editor-integration) with VS Code, GNU Emacs, Sublime Text. 13 14 Follow the news and releases on our [twitter](https://twitter.com/golangci) and our [blog](https://medium.com/golangci). 15 16 Sponsored by [GolangCI.com](https://golangci.com): SaaS service for running linters on GitHub pull requests. Free for Open Source. 17 18 <a href="https://golangci.com/"><img src="docs/go.png" width="250px"></a> 19 20 - [GolangCI-Lint](#golangci-lint) 21 - [Demo](#demo) 22 - [Install](#install) 23 - [Binary](#binary) 24 - [macOS](#macos) 25 - [Docker](#docker) 26 - [Go](#go) 27 - [Trusted By](#trusted-by) 28 - [Quick Start](#quick-start) 29 - [Editor Integration](#editor-integration) 30 - [Shell Completion](#shell-completion) 31 - [macOS](#macos-1) 32 - [Linux](#linux) 33 - [Comparison](#comparison) 34 - [`golangci-lint` vs `gometalinter`](#golangci-lint-vs-gometalinter) 35 - [`golangci-lint` vs Running Linters Manually](#golangci-lint-vs-running-linters-manually) 36 - [Performance](#performance) 37 - [Comparison with gometalinter](#comparison-with-gometalinter) 38 - [Why golangci-lint is faster](#why-golangci-lint-is-faster) 39 - [Memory Usage of Golangci-lint](#memory-usage-of-golangci-lint) 40 - [Internals](#internals) 41 - [Supported Linters](#supported-linters) 42 - [Enabled By Default Linters](#enabled-by-default-linters) 43 - [Disabled By Default Linters (`-E/--enable`)](#disabled-by-default-linters--e--enable) 44 - [Configuration](#configuration) 45 - [Command-Line Options](#command-line-options) 46 - [Config File](#config-file) 47 - [False Positives](#false-positives) 48 - [Nolint](#nolint) 49 - [FAQ](#faq) 50 - [Thanks](#thanks) 51 - [Changelog](#changelog) 52 - [Debug](#debug) 53 - [Future Plans](#future-plans) 54 - [Contact Information](#contact-information) 55 - [License Scan](#license-scan) 56 57 ## Demo 58 59 <p align="center"> 60 <img src="./docs/demo.svg" width="100%"> 61 </p> 62 63 Short 1.5 min video demo of analyzing [beego](https://github.com/astaxie/beego). 64 [![asciicast](https://asciinema.org/a/183662.png)](https://asciinema.org/a/183662) 65 66 ## Install 67 68 ### Binary 69 70 Most installations are done for CI (e.g. Travis CI, CircleCI). It's important to have reproducible CI: 71 don't start to fail all builds at the same time. With golangci-lint this can happen if you 72 use deprecated option `--enable-all` and a new linter is added or even without `--enable-all`: when one upstream linter is upgraded. 73 74 It's highly recommended to install a specific version of golangci-lint available on the [releases page](https://github.com/golangci/golangci-lint/releases). 75 76 Here is the recommended way to install golangci-lint v1.26.0: 77 78 ```bash 79 # binary will be $(go env GOPATH)/bin/golangci-lint 80 curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.26.0 81 82 # or install it into ./bin/ 83 curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s v1.26.0 84 85 # In alpine linux (as it does not come with curl by default) 86 wget -O- -nv https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s v1.26.0 87 88 golangci-lint --version 89 ``` 90 91 It is advised that you periodically update version of golangci-lint as the project is under active development 92 and is constantly being improved. For any problems with golangci-lint, check out recent [GitHub issues](https://github.com/golangci/golangci-lint/issues) and update if needed. 93 94 ### macOS 95 96 You can also install a binary release on macOS using [brew](https://brew.sh/): 97 98 ```bash 99 brew install golangci/tap/golangci-lint 100 brew upgrade golangci/tap/golangci-lint 101 ``` 102 103 ### Docker 104 105 ```bash 106 docker run --rm -v $(pwd):/app -w /app golangci/golangci-lint:v1.26.0 golangci-lint run -v 107 ``` 108 109 ### Go 110 111 Go source installations are supported for the two most recent Go releases. 112 113 ```bash 114 GO111MODULE=on go get github.com/golangci/golangci-lint/cmd/golangci-lint@v1.26.0 115 ``` 116 117 ## Trusted By 118 119 The following companies/products use golangci-lint: 120 121 * [Google](https://github.com/GoogleContainerTools/skaffold) 122 * [Facebook](https://github.com/facebookincubator/fbender) 123 * [Red Hat OpenShift](https://github.com/openshift/telemeter) 124 * [Yahoo](https://github.com/yahoo/yfuzz) 125 * [IBM](https://github.com/ibm-developer/ibm-cloud-env-golang) 126 * [Intuit](https://github.com/intuit) 127 * [Xiaomi](https://github.com/XiaoMi/soar) 128 * [Baidu](https://github.com/baidu/bfe) 129 * [Samsung](https://github.com/samsung-cnct/cluster-api-provider-ssh) 130 * [Arduino](https://github.com/arduino/arduino-cli) 131 * [Eclipse Foundation](https://github.com/eclipse/che-go-jsonrpc) 132 * [WooCart](https://github.com/woocart/gsutil) 133 * [Percona](https://github.com/percona/pmm-managed) 134 * [Serverless](https://github.com/serverless/event-gateway) 135 * [ScyllaDB](https://github.com/scylladb/gocqlx) 136 * [NixOS](https://github.com/NixOS/nixpkgs-channels) 137 * [The New York Times](https://github.com/NYTimes/encoding-wrapper) 138 * [Istio](https://github.com/istio/istio) 139 * [SoundCloud](https://github.com/soundcloud/periskop) 140 * [Mattermost](https://github.com/mattermost/mattermost-server) 141 142 The following great projects use golangci-lint: 143 144 * [alecthomas/participle](https://github.com/alecthomas/participle) 145 * [asobti/kube-monkey](https://github.com/asobti/kube-monkey) 146 * [banzaicloud/pipeline](https://github.com/banzaicloud/pipeline) 147 * [caicloud/cyclone](https://github.com/caicloud/cyclone) 148 * [getantibody/antibody](https://github.com/getantibody/antibody) 149 * [goreleaser/goreleaser](https://github.com/goreleaser/goreleaser) 150 * [go-swagger/go-swagger](https://github.com/go-swagger/go-swagger) 151 * [kubeedge/kubeedge](https://github.com/kubeedge/kubeedge) 152 * [kubernetes-sigs/kustomize](https://github.com/kubernetes-sigs/kustomize) 153 * [dunglas/mercure](https://github.com/dunglas/mercure) 154 * [posener/complete](https://github.com/posener/complete) 155 * [segmentio/terraform-docs](https://github.com/segmentio/terraform-docs) 156 * [tsuru/tsuru](https://github.com/tsuru/tsuru) 157 * [twpayne/chezmoi](https://github.com/twpayne/chezmoi) 158 * [virtual-kubelet/virtual-kubelet](https://github.com/virtual-kubelet/virtual-kubelet) 159 * [xenolf/lego](https://github.com/xenolf/lego) 160 * [y0ssar1an/q](https://github.com/y0ssar1an/q) 161 162 ## Quick Start 163 164 To run golangci-lint execute: 165 166 ```bash 167 golangci-lint run 168 ``` 169 170 It's an equivalent of executing: 171 172 ```bash 173 golangci-lint run ./... 174 ``` 175 176 You can choose which directories and files to analyze: 177 178 ```bash 179 golangci-lint run dir1 dir2/... dir3/file1.go 180 ``` 181 182 Directories are NOT analyzed recursively. To analyze them recursively append `/...` to their path. 183 184 GolangCI-Lint can be used with zero configuration. By default the following linters are enabled: 185 186 ```bash 187 $ golangci-lint help linters 188 Enabled by default linters: 189 deadcode: Finds unused code [fast: true, auto-fix: false] 190 errcheck: Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases [fast: true, auto-fix: false] 191 gosimple (megacheck): Linter for Go source code that specializes in simplifying a code [fast: true, auto-fix: false] 192 govet (vet, vetshadow): Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string [fast: true, auto-fix: false] 193 ineffassign: Detects when assignments to existing variables are not used [fast: true, auto-fix: false] 194 staticcheck (megacheck): Staticcheck is a go vet on steroids, applying a ton of static analysis checks [fast: true, auto-fix: false] 195 structcheck: Finds unused struct fields [fast: true, auto-fix: false] 196 typecheck: Like the front-end of a Go compiler, parses and type-checks Go code [fast: true, auto-fix: false] 197 unused (megacheck): Checks Go code for unused constants, variables, functions and types [fast: false, auto-fix: false] 198 varcheck: Finds unused global variables and constants [fast: true, auto-fix: false] 199 ``` 200 201 and the following linters are disabled by default: 202 203 ```bash 204 $ golangci-lint help linters 205 ... 206 Disabled by default linters: 207 asciicheck: Simple linter to check that your code does not contain non-ASCII identifiers [fast: true, auto-fix: false] 208 bodyclose: checks whether HTTP response body is closed successfully [fast: true, auto-fix: false] 209 depguard: Go linter that checks if package imports are in a list of acceptable packages [fast: true, auto-fix: false] 210 dogsled: Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) [fast: true, auto-fix: false] 211 dupl: Tool for code clone detection [fast: true, auto-fix: false] 212 funlen: Tool for detection of long functions [fast: true, auto-fix: false] 213 gochecknoglobals: Checks that no globals are present in Go code [fast: true, auto-fix: false] 214 gochecknoinits: Checks that no init functions are present in Go code [fast: true, auto-fix: false] 215 gocognit: Computes and checks the cognitive complexity of functions [fast: true, auto-fix: false] 216 goconst: Finds repeated strings that could be replaced by a constant [fast: true, auto-fix: false] 217 gocritic: The most opinionated Go source code linter [fast: true, auto-fix: false] 218 gocyclo: Computes and checks the cyclomatic complexity of functions [fast: true, auto-fix: false] 219 godot: Check if comments end in a period [fast: true, auto-fix: false] 220 godox: Tool for detection of FIXME, TODO and other comment keywords [fast: true, auto-fix: false] 221 goerr113: Golang linter to check the errors handling expressions [fast: true, auto-fix: false] 222 gofmt: Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification [fast: true, auto-fix: true] 223 goimports: Goimports does everything that gofmt does. Additionally it checks unused imports [fast: true, auto-fix: true] 224 golint: Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes [fast: true, auto-fix: false] 225 gomnd: An analyzer to detect magic numbers. [fast: true, auto-fix: false] 226 gomodguard: Allow and block list linter for direct Go module dependencies. [fast: true, auto-fix: false] 227 goprintffuncname: Checks that printf-like functions are named with `f` at the end [fast: true, auto-fix: false] 228 gosec (gas): Inspects source code for security problems [fast: true, auto-fix: false] 229 interfacer: Linter that suggests narrower interface types [fast: true, auto-fix: false] 230 lll: Reports long lines [fast: true, auto-fix: false] 231 maligned: Tool to detect Go structs that would take less memory if their fields were sorted [fast: true, auto-fix: false] 232 misspell: Finds commonly misspelled English words in comments [fast: true, auto-fix: true] 233 nakedret: Finds naked returns in functions greater than a specified function length [fast: true, auto-fix: false] 234 nestif: Reports deeply nested if statements [fast: true, auto-fix: false] 235 nolintlint: Reports ill-formed or insufficient nolint directives [fast: true, auto-fix: false] 236 prealloc: Finds slice declarations that could potentially be preallocated [fast: true, auto-fix: false] 237 rowserrcheck: checks whether Err of rows is checked successfully [fast: true, auto-fix: false] 238 scopelint: Scopelint checks for unpinned variables in go programs [fast: true, auto-fix: false] 239 stylecheck: Stylecheck is a replacement for golint [fast: true, auto-fix: false] 240 testpackage: linter that makes you use a separate _test package [fast: true, auto-fix: false] 241 unconvert: Remove unnecessary type conversions [fast: true, auto-fix: false] 242 unparam: Reports unused function parameters [fast: true, auto-fix: false] 243 whitespace: Tool for detection of leading and trailing whitespace [fast: true, auto-fix: true] 244 wsl: Whitespace Linter - Forces you to use empty lines! [fast: true, auto-fix: false] 245 ``` 246 247 Pass `-E/--enable` to enable linter and `-D/--disable` to disable: 248 249 ```bash 250 golangci-lint run --disable-all -E errcheck 251 ``` 252 253 ## Editor Integration 254 255 1. [Go for Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=ms-vscode.Go). 256 Recommended settings for VS Code are: 257 258 ```json 259 "go.lintTool":"golangci-lint", 260 "go.lintFlags": [ 261 "--fast" 262 ] 263 ``` 264 265 Using it in an editor without `--fast` can freeze your editor. 266 Golangci-lint automatically discovers `.golangci.yml` config for edited file: you don't need to configure it in VS Code settings. 267 2. Sublime Text - [plugin](https://github.com/alecthomas/SublimeLinter-contrib-golang-cilint) for SublimeLinter. 268 3. GoLand 269 * Add [File Watcher](https://www.jetbrains.com/help/go/settings-tools-file-watchers.html) using existing `golangci-lint` template. 270 * If your version of GoLand does not have the `golangci-lint` [File Watcher](https://www.jetbrains.com/help/go/settings-tools-file-watchers.html) template you can configure your own and use arguments `run --disable=typecheck $FileDir$`. 271 4. GNU Emacs 272 * [Spacemacs](https://github.com/syl20bnr/spacemacs/blob/develop/layers/+lang/go/README.org#pre-requisites) 273 * [flycheck checker](https://github.com/weijiangan/flycheck-golangci-lint). 274 5. Vim 275 * [vim-go](https://github.com/fatih/vim-go) 276 * syntastic [merged pull request](https://github.com/vim-syntastic/syntastic/pull/2190) with golangci-lint support 277 * ale [merged pull request](https://github.com/w0rp/ale/pull/1890) with golangci-lint support 278 6. Atom - [go-plus](https://atom.io/packages/go-plus) supports golangci-lint. 279 280 ## Shell Completion 281 282 `golangci-lint` can generate bash completion file. 283 284 ### macOS 285 286 There are two versions of `bash-completion`, v1 and v2. V1 is for Bash 3.2 (which is the default on macOS), and v2 is for Bash 4.1+. The `golangci-lint` completion script doesn’t work correctly with bash-completion v1 and Bash 3.2. It requires bash-completion v2 and Bash 4.1+. Thus, to be able to correctly use `golangci-lint` completion on macOS, you have to install and use Bash 4.1+ ([instructions](https://itnext.io/upgrading-bash-on-macos-7138bd1066ba)). The following instructions assume that you use Bash 4.1+ (that is, any Bash version of 4.1 or newer). 287 288 Install `bash-completion v2`: 289 290 ```bash 291 brew install bash-completion@2 292 echo 'export BASH_COMPLETION_COMPAT_DIR="/usr/local/etc/bash_completion.d"' >>~/.bashrc 293 echo '[[ -r "/usr/local/etc/profile.d/bash_completion.sh" ]] && . "/usr/local/etc/profile.d/bash_completion.sh"' >>~/.bashrc 294 exec bash # reload and replace (if it was updated) shell 295 type _init_completion && echo "completion is OK" # verify that bash-completion v2 is correctly installed 296 ``` 297 298 Add `golangci-lint` bash completion: 299 300 ```bash 301 echo 'source <(golangci-lint completion bash)' >>~/.bashrc 302 source ~/.bashrc 303 ``` 304 305 ### Linux 306 307 See [kubectl instructions](https://kubernetes.io/docs/tasks/tools/install-kubectl/#enabling-shell-autocompletion) and don't forget to replace `kubectl` with `golangci-lint`. 308 309 ## Comparison 310 311 ### `golangci-lint` vs `gometalinter` 312 313 GolangCI-Lint was created to fix the following issues with `gometalinter`: 314 315 1. Slow work: `gometalinter` usually works for minutes in average projects. 316 **GolangCI-Lint works [2-7x times faster](#performance)** by [reusing work](#internals). 317 2. Huge memory consumption: parallel linters don't share the same program representation and can consume 318 `n` times more memory (`n` - concurrency). GolangCI-Lint fixes it by sharing representation and **consumes 26% less memory**. 319 3. Doesn't use real bounded concurrency: if you set it to `n` it can take up to `n*n` threads because of 320 forced threads in specific linters. `gometalinter` can't do anything about it because it runs linters as 321 black boxes in forked processes. In GolangCI-Lint we run all linters in one process and completely control 322 them. Configured concurrency will be correctly bounded. 323 This issue is important because you often want to set concurrency to the CPUs count minus one to 324 ensure you **do not freeze your PC** and be able to work on it while analyzing code. 325 4. Lack of nice output. We like how the `gcc` and `clang` compilers format their warnings: **using colors, 326 printing warning lines and showing the position in line**. 327 5. Too many issues. GolangCI-Lint cuts a lot of issues by using default exclude list of common false-positives. 328 By default, it has enabled **smart issues processing**: merge multiple issues for one line, merge issues with the 329 same text or from the same linter. All of these smart processors can be configured by the user. 330 6. Integration into large codebases. A good way to start using linters in a large project is not to fix a plethora 331 of existing issues, but to set up CI and **fix only issues in new commits**. You can use `revgrep` for it, but it's 332 yet another utility to install and configure. With `golangci-lint` it's much easier: `revgrep` is already built into 333 `golangci-lint` and you can use it with one option (`-n, --new` or `--new-from-rev`). 334 7. Installation. With `gometalinter`, you need to run a linters installation step. It's easy to forget this step and 335 end up with stale linters. It also complicates CI setup. GolangCI-Lint requires **no installation of linters**. 336 8. **Yaml or toml config**. Gometalinter's JSON isn't convenient for config files. 337 338 ### `golangci-lint` vs Running Linters Manually 339 340 1. It will be much slower because `golangci-lint` runs all linters in parallel and shares 50-80% of linters work. 341 2. It will have less control and more false-positives: some linters can't be properly configured without hacks. 342 3. It will take more time because of different usages and need of tracking of versions of `n` linters. 343 344 ## Performance 345 346 Benchmarks were executed on MacBook Pro (Retina, 13-inch, Late 2013), 2,4 GHz Intel Core i5, 8 GB 1600 MHz DDR3. 347 It has 4 cores and concurrent linting as a default consuming all cores. 348 Benchmark was run (and measured) automatically, see the code 349 [here](https://github.com/golangci/golangci-lint/blob/master/test/bench/bench_test.go) (`BenchmarkWithGometalinter`). 350 351 We measure peak memory usage (RSS) by tracking of processes RSS every 5 ms. 352 353 ### Comparison with gometalinter 354 355 We compare golangci-lint and gometalinter in default mode, but explicitly enable all linters because of small differences in the default configuration. 356 357 ```bash 358 $ golangci-lint run --no-config --issues-exit-code=0 --timeout=30m \ 359 --disable-all --enable=deadcode --enable=gocyclo --enable=golint --enable=varcheck \ 360 --enable=structcheck --enable=maligned --enable=errcheck --enable=dupl --enable=ineffassign \ 361 --enable=interfacer --enable=unconvert --enable=goconst --enable=gosec --enable=megacheck 362 $ gometalinter --deadline=30m --vendor --cyclo-over=30 --dupl-threshold=150 \ 363 --exclude=<default golangci-lint excludes> --skip=testdata --skip=builtin \ 364 --disable-all --enable=deadcode --enable=gocyclo --enable=golint --enable=varcheck \ 365 --enable=structcheck --enable=maligned --enable=errcheck --enable=dupl --enable=ineffassign \ 366 --enable=interfacer --enable=unconvert --enable=goconst --enable=gosec --enable=megacheck 367 ./... 368 ``` 369 370 | Repository | GolangCI Time | GolangCI Is Faster than Gometalinter | GolangCI Memory | GolangCI eats less memory than Gometalinter | 371 | ---------- | ------------- | ------------------------------------ | --------------- | ------------------------------------------- | 372 | gometalinter repo, 4 kLoC | 6s | **6.4x** | 0.7GB | 33% | 373 | self-repo, 4 kLoC | 12s | **7.5x** | 1.2GB | 41% | 374 | beego, 50 kLoC | 10s | **4.2x** | 1.4GB | 9% | 375 | hugo, 70 kLoC | 15s | **6.1x** | 1.6GB | 44% | 376 | consul, 127 kLoC | 58s | **4x** | 2.7GB | 41% | 377 | terraform, 190 kLoC | 2m13s | **1.6x** | 4.8GB | 0% | 378 | go-ethereum, 250 kLoC | 33s | **5x** | 3.6GB | 0% | 379 | go source (`$GOROOT/src`), 1300 kLoC | 2m45s | **2x** | 4.7GB | 0% | 380 381 **On average golangci-lint is 4.6 times faster** than gometalinter. Maximum difference is in the 382 self-repo: **7.5 times faster**, minimum difference is in terraform source code repo: 1.8 times faster. 383 384 On average golangci-lint consumes 26% less memory. 385 386 ### Why golangci-lint is faster 387 388 Golangci-lint directly calls linters (no forking) and reuses 80% of work by parsing program only once. 389 Read [this section](#internals) for details. 390 391 ### Memory Usage of Golangci-lint 392 393 A trade-off between memory usage and execution time can be controlled by [`GOGC`](https://golang.org/pkg/runtime/#hdr-Environment_Variables) environment variable. 394 Less `GOGC` values trigger garbage collection more frequently and golangci-lint consumes less memory and more CPU. Below is the trade-off table for running on this repo: 395 396 |`GOGC`|Peak Memory, GB|Executon Time, s| 397 |------|---------------|----------------| 398 |`5` |1.1 |60 | 399 |`10` |1.1 |34 | 400 |`20` |1.3 |25 | 401 |`30` |1.6 |20.2 | 402 |`50` |2.0 |17.1 | 403 |`80` |2.2 |14.1 | 404 |`100` (default)|2.2 |13.8 | 405 |`off` |3.2 |9.3 | 406 407 ## Internals 408 409 1. Work sharing 410 The key difference with gometalinter is that golangci-lint shares work between specific linters (golint, govet, ...). 411 We don't fork to call specific linter but use its API. 412 For small and medium projects 50-90% of work between linters can be reused. 413 414 * load `[]*packages.Package` by `go/packages` once 415 416 We load program (parsing all files and type-checking) only once for all linters. For the most of linters 417 it's the most heavy operation: it takes 5 seconds on 8 kLoC repo and 11 seconds on `$GOROOT/src`. 418 * build `ssa.Program` once 419 420 Some linters (megacheck, interfacer, unparam) work on SSA representation. 421 Building of this representation takes 1.5 seconds on 8 kLoC repo and 6 seconds on `$GOROOT/src`. 422 423 * parse source code and build AST once 424 425 Parsing one source file takes 200 us on average. Parsing of all files in `$GOROOT/src` takes 2 seconds. 426 Currently we parse each file more than once because it's not the bottleneck. But we already save a lot of 427 extra parsing. We're planning to parse each file only once. 428 429 * walk files and directories once 430 431 It takes 300-1000 ms for `$GOROOT/src`. 432 2. Smart linters scheduling 433 434 We schedule linters by a special algorithm which takes estimated execution time into account. It allows 435 to save 10-30% of time when one of heavy linters (megacheck etc) is enabled. 436 437 3. Don't fork to run shell commands 438 439 All linters has their version fixed with go modules, they are builtin 440 and you don't need to install them separately. 441 442 ## Supported Linters 443 444 To see a list of supported linters and which linters are enabled/disabled: 445 446 ```bash 447 golangci-lint help linters 448 ``` 449 450 ### Enabled By Default Linters 451 452 - [govet](https://golang.org/cmd/vet/) - Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string 453 - [errcheck](https://github.com/kisielk/errcheck) - Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases 454 - [staticcheck](https://staticcheck.io/) - Staticcheck is a go vet on steroids, applying a ton of static analysis checks 455 - [unused](https://github.com/dominikh/go-tools/tree/master/unused) - Checks Go code for unused constants, variables, functions and types 456 - [gosimple](https://github.com/dominikh/go-tools/tree/master/simple) - Linter for Go source code that specializes in simplifying a code 457 - [structcheck](https://github.com/opennota/check) - Finds unused struct fields 458 - [varcheck](https://github.com/opennota/check) - Finds unused global variables and constants 459 - [ineffassign](https://github.com/gordonklaus/ineffassign) - Detects when assignments to existing variables are not used 460 - [deadcode](https://github.com/remyoudompheng/go-misc/tree/master/deadcode) - Finds unused code 461 - typecheck - Like the front-end of a Go compiler, parses and type-checks Go code 462 463 ### Disabled By Default Linters (`-E/--enable`) 464 465 - [bodyclose](https://github.com/timakin/bodyclose) - checks whether HTTP response body is closed successfully 466 - [golint](https://github.com/golang/lint) - Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes 467 - [rowserrcheck](https://github.com/jingyugao/rowserrcheck) - checks whether Err of rows is checked successfully 468 - [stylecheck](https://github.com/dominikh/go-tools/tree/master/stylecheck) - Stylecheck is a replacement for golint 469 - [gosec](https://github.com/securego/gosec) - Inspects source code for security problems 470 - [interfacer](https://github.com/mvdan/interfacer) - Linter that suggests narrower interface types 471 - [unconvert](https://github.com/mdempsky/unconvert) - Remove unnecessary type conversions 472 - [dupl](https://github.com/mibk/dupl) - Tool for code clone detection 473 - [goconst](https://github.com/jgautheron/goconst) - Finds repeated strings that could be replaced by a constant 474 - [gocyclo](https://github.com/alecthomas/gocyclo) - Computes and checks the cyclomatic complexity of functions 475 - [gocognit](https://github.com/uudashr/gocognit) - Computes and checks the cognitive complexity of functions 476 - [asciicheck](https://github.com/tdakkota/asciicheck) - Simple linter to check that your code does not contain non-ASCII identifiers 477 - [gofmt](https://golang.org/cmd/gofmt/) - Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification 478 - [goimports](https://godoc.org/golang.org/x/tools/cmd/goimports) - Goimports does everything that gofmt does. Additionally it checks unused imports 479 - [maligned](https://github.com/mdempsky/maligned) - Tool to detect Go structs that would take less memory if their fields were sorted 480 - [depguard](https://github.com/OpenPeeDeeP/depguard) - Go linter that checks if package imports are in a list of acceptable packages 481 - [misspell](https://github.com/client9/misspell) - Finds commonly misspelled English words in comments 482 - [lll](https://github.com/walle/lll) - Reports long lines 483 - [unparam](https://github.com/mvdan/unparam) - Reports unused function parameters 484 - [dogsled](https://github.com/alexkohler/dogsled) - Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) 485 - [nakedret](https://github.com/alexkohler/nakedret) - Finds naked returns in functions greater than a specified function length 486 - [prealloc](https://github.com/alexkohler/prealloc) - Finds slice declarations that could potentially be preallocated 487 - [scopelint](https://github.com/kyoh86/scopelint) - Scopelint checks for unpinned variables in go programs 488 - [gocritic](https://github.com/go-critic/go-critic) - The most opinionated Go source code linter 489 - [gochecknoinits](https://github.com/leighmcculloch/gochecknoinits) - Checks that no init functions are present in Go code 490 - [gochecknoglobals](https://github.com/leighmcculloch/gochecknoglobals) - Checks that no globals are present in Go code 491 - [godox](https://github.com/matoous/godox) - Tool for detection of FIXME, TODO and other comment keywords 492 - [funlen](https://github.com/ultraware/funlen) - Tool for detection of long functions 493 - [whitespace](https://github.com/ultraware/whitespace) - Tool for detection of leading and trailing whitespace 494 - [wsl](https://github.com/bombsimon/wsl) - Whitespace Linter - Forces you to use empty lines! 495 - [goprintffuncname](https://github.com/jirfag/go-printf-func-name) - Checks that printf-like functions are named with `f` at the end 496 - [gomnd](https://github.com/tommy-muehle/go-mnd) - An analyzer to detect magic numbers. 497 - [goerr113](https://github.com/Djarvur/go-err113) - Golang linter to check the errors handling expressions 498 - [gomodguard](https://github.com/ryancurrah/gomodguard) - Allow and block list linter for direct Go module dependencies. 499 - [godot](https://github.com/tetafro/godot) - Check if comments end in a period 500 - [testpackage](https://github.com/maratori/testpackage) - linter that makes you use a separate _test package 501 - [nestif](https://github.com/nakabonne/nestif) - Reports deeply nested if statements 502 - [nolintlint](https://github.com/golangci-lint/pkg/golinters/nolintlint) - Reports ill-formed or insufficient nolint directives 503 504 ## Configuration 505 506 The config file has lower priority than command-line options. If the same bool/string/int option is provided on the command-line 507 and in the config file, the option from command-line will be used. 508 Slice options (e.g. list of enabled/disabled linters) are combined from the command-line and config file. 509 510 To see a list of enabled by your configuration linters: 511 512 ```bash 513 golangci-lint linters 514 ``` 515 516 ### Command-Line Options 517 518 ```bash 519 golangci-lint run -h 520 Usage: 521 golangci-lint run [flags] 522 523 Flags: 524 --out-format string Format of output: colored-line-number|line-number|json|tab|checkstyle|code-climate|junit-xml|github-actions (default "colored-line-number") 525 --print-issued-lines Print lines of code with issue (default true) 526 --print-linter-name Print linter name in issue line (default true) 527 --uniq-by-line Make issues output unique by line (default true) 528 --modules-download-mode string Modules download mode. If not empty, passed as -mod=<mode> to go tools 529 --issues-exit-code int Exit code when issues were found (default 1) 530 --build-tags strings Build tags 531 --timeout duration Timeout for total work (default 1m0s) 532 --tests Analyze tests (*_test.go) (default true) 533 --print-resources-usage Print avg and max memory usage of golangci-lint and total time 534 -c, --config PATH Read config from file path PATH 535 --no-config Don't read config 536 --skip-dirs strings Regexps of directories to skip 537 --skip-dirs-use-default Use or not use default excluded directories: 538 - (^|/)vendor($|/) 539 - (^|/)third_party($|/) 540 - (^|/)testdata($|/) 541 - (^|/)examples($|/) 542 - (^|/)Godeps($|/) 543 - (^|/)builtin($|/) 544 (default true) 545 --skip-files strings Regexps of files to skip 546 -E, --enable strings Enable specific linter 547 -D, --disable strings Disable specific linter 548 --disable-all Disable all linters 549 -p, --presets strings Enable presets (bugs|complexity|format|performance|style|unused) of linters. Run 'golangci-lint linters' to see them. This option implies option --disable-all 550 --fast Run only fast linters from enabled linters set (first run won't be fast) 551 -e, --exclude strings Exclude issue by regexp 552 --exclude-use-default Use or not use default excludes: 553 # EXC0001 errcheck: Almost all programs ignore errors on these functions and in most cases it's ok 554 - Error return value of .((os\.)?std(out|err)\..*|.*Close|.*Flush|os\.Remove(All)?|.*printf?|os\.(Un)?Setenv). is not checked 555 556 # EXC0002 golint: Annoying issue about not having a comment. The rare codebase has such comments 557 - (comment on exported (method|function|type|const)|should have( a package)? comment|comment should be of the form) 558 559 # EXC0003 golint: False positive when tests are defined in package 'test' 560 - func name will be used as test\.Test.* by other packages, and that stutters; consider calling this 561 562 # EXC0004 govet: Common false positives 563 - (possible misuse of unsafe.Pointer|should have signature) 564 565 # EXC0005 staticcheck: Developers tend to write in C-style with an explicit 'break' in a 'switch', so it's ok to ignore 566 - ineffective break statement. Did you mean to break out of the outer loop 567 568 # EXC0006 gosec: Too many false-positives on 'unsafe' usage 569 - Use of unsafe calls should be audited 570 571 # EXC0007 gosec: Too many false-positives for parametrized shell calls 572 - Subprocess launch(ed with variable|ing should be audited) 573 574 # EXC0008 gosec: Duplicated errcheck checks 575 - (G104|G307) 576 577 # EXC0009 gosec: Too many issues in popular repos 578 - (Expect directory permissions to be 0750 or less|Expect file permissions to be 0600 or less) 579 580 # EXC0010 gosec: False positive is triggered by 'src, err := ioutil.ReadFile(filename)' 581 - Potential file inclusion via variable 582 (default true) 583 --exclude-case-sensitive If set to true exclude and exclude rules regular expressions are case sensitive 584 --max-issues-per-linter int Maximum issues count per one linter. Set to 0 to disable (default 50) 585 --max-same-issues int Maximum count of issues with the same text. Set to 0 to disable (default 3) 586 -n, --new Show only new issues: if there are unstaged changes or untracked files, only those changes are analyzed, else only changes in HEAD~ are analyzed. 587 It's a super-useful option for integration of golangci-lint into existing large codebase. 588 It's not practical to fix all existing issues at the moment of integration: much better to not allow issues in new code. 589 For CI setups, prefer --new-from-rev=HEAD~, as --new can skip linting the current patch if any scripts generate unstaged files before golangci-lint runs. 590 --new-from-rev REV Show only new issues created after git revision REV 591 --new-from-patch PATH Show only new issues created in git patch with file path PATH 592 --fix Fix found issues (if it's supported by the linter) 593 -h, --help help for run 594 595 Global Flags: 596 --color string Use color when printing; can be 'always', 'auto', or 'never' (default "auto") 597 -j, --concurrency int Concurrency (default NumCPU) (default 8) 598 --cpu-profile-path string Path to CPU profile output file 599 --mem-profile-path string Path to memory profile output file 600 --trace-path string Path to trace output file 601 -v, --verbose verbose output 602 --version Print version 603 604 ``` 605 606 ### Config File 607 608 GolangCI-Lint looks for config files in the following paths from the current working directory: 609 610 * `.golangci.yml` 611 * `.golangci.toml` 612 * `.golangci.json` 613 614 GolangCI-Lint also searches for config files in all directories from the directory of the first analyzed path up to the root. 615 To see which config file is being used and where it was sourced from run golangci-lint with `-v` option. 616 617 Config options inside the file are identical to command-line options. 618 You can configure specific linters' options only within the config file (not the command-line). 619 620 There is a [`.golangci.example.yml`](https://github.com/golangci/golangci-lint/blob/master/.golangci.example.yml) example 621 config file with all supported options, their description and default value: 622 623 ```yaml 624 # This file contains all available configuration options 625 # with their default values. 626 627 # options for analysis running 628 run: 629 # default concurrency is a available CPU number 630 concurrency: 4 631 632 # timeout for analysis, e.g. 30s, 5m, default is 1m 633 timeout: 1m 634 635 # exit code when at least one issue was found, default is 1 636 issues-exit-code: 1 637 638 # include test files or not, default is true 639 tests: true 640 641 # list of build tags, all linters use it. Default is empty list. 642 build-tags: 643 - mytag 644 645 # which dirs to skip: issues from them won't be reported; 646 # can use regexp here: generated.*, regexp is applied on full path; 647 # default value is empty list, but default dirs are skipped independently 648 # from this option's value (see skip-dirs-use-default). 649 skip-dirs: 650 - src/external_libs 651 - autogenerated_by_my_lib 652 653 # default is true. Enables skipping of directories: 654 # vendor$, third_party$, testdata$, examples$, Godeps$, builtin$ 655 skip-dirs-use-default: true 656 657 # which files to skip: they will be analyzed, but issues from them 658 # won't be reported. Default value is empty list, but there is 659 # no need to include all autogenerated files, we confidently recognize 660 # autogenerated files. If it's not please let us know. 661 skip-files: 662 - ".*\\.my\\.go$" 663 - lib/bad.go 664 665 # by default isn't set. If set we pass it to "go list -mod={option}". From "go help modules": 666 # If invoked with -mod=readonly, the go command is disallowed from the implicit 667 # automatic updating of go.mod described above. Instead, it fails when any changes 668 # to go.mod are needed. This setting is most useful to check that go.mod does 669 # not need updates, such as in a continuous integration and testing system. 670 # If invoked with -mod=vendor, the go command assumes that the vendor 671 # directory holds the correct copies of dependencies and ignores 672 # the dependency descriptions in go.mod. 673 modules-download-mode: readonly|release|vendor 674 675 676 # output configuration options 677 output: 678 # colored-line-number|line-number|json|tab|checkstyle|code-climate, default is "colored-line-number" 679 format: colored-line-number 680 681 # print lines of code with issue, default is true 682 print-issued-lines: true 683 684 # print linter name in the end of issue text, default is true 685 print-linter-name: true 686 687 # make issues output unique by line, default is true 688 uniq-by-line: true 689 690 691 # all available settings of specific linters 692 linters-settings: 693 dogsled: 694 # checks assignments with too many blank identifiers; default is 2 695 max-blank-identifiers: 2 696 dupl: 697 # tokens count to trigger issue, 150 by default 698 threshold: 100 699 errcheck: 700 # report about not checking of errors in type assertions: `a := b.(MyStruct)`; 701 # default is false: such cases aren't reported by default. 702 check-type-assertions: false 703 704 # report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`; 705 # default is false: such cases aren't reported by default. 706 check-blank: false 707 708 # [deprecated] comma-separated list of pairs of the form pkg:regex 709 # the regex is used to ignore names within pkg. (default "fmt:.*"). 710 # see https://github.com/kisielk/errcheck#the-deprecated-method for details 711 ignore: fmt:.*,io/ioutil:^Read.* 712 713 # path to a file containing a list of functions to exclude from checking 714 # see https://github.com/kisielk/errcheck#excluding-functions for details 715 exclude: /path/to/file.txt 716 funlen: 717 lines: 60 718 statements: 40 719 gocognit: 720 # minimal code complexity to report, 30 by default (but we recommend 10-20) 721 min-complexity: 10 722 nestif: 723 # minimal complexity of if statements to report, 5 by default 724 min-complexity: 4 725 goconst: 726 # minimal length of string constant, 3 by default 727 min-len: 3 728 # minimal occurrences count to trigger, 3 by default 729 min-occurrences: 3 730 gocritic: 731 # Which checks should be enabled; can't be combined with 'disabled-checks'; 732 # See https://go-critic.github.io/overview#checks-overview 733 # To check which checks are enabled run `GL_DEBUG=gocritic golangci-lint run` 734 # By default list of stable checks is used. 735 enabled-checks: 736 - rangeValCopy 737 738 # Which checks should be disabled; can't be combined with 'enabled-checks'; default is empty 739 disabled-checks: 740 - regexpMust 741 742 # Enable multiple checks by tags, run `GL_DEBUG=gocritic golangci-lint run` to see all tags and checks. 743 # Empty list by default. See https://github.com/go-critic/go-critic#usage -> section "Tags". 744 enabled-tags: 745 - performance 746 disabled-tags: 747 - experimental 748 749 settings: # settings passed to gocritic 750 captLocal: # must be valid enabled check name 751 paramsOnly: true 752 rangeValCopy: 753 sizeThreshold: 32 754 gocyclo: 755 # minimal code complexity to report, 30 by default (but we recommend 10-20) 756 min-complexity: 10 757 godot: 758 # check all top-level comments, not only declarations 759 check-all: false 760 godox: 761 # report any comments starting with keywords, this is useful for TODO or FIXME comments that 762 # might be left in the code accidentally and should be resolved before merging 763 keywords: # default keywords are TODO, BUG, and FIXME, these can be overwritten by this setting 764 - NOTE 765 - OPTIMIZE # marks code that should be optimized before merging 766 - HACK # marks hack-arounds that should be removed before merging 767 gofmt: 768 # simplify code: gofmt with `-s` option, true by default 769 simplify: true 770 goimports: 771 # put imports beginning with prefix after 3rd-party packages; 772 # it's a comma-separated list of prefixes 773 local-prefixes: github.com/org/project 774 golint: 775 # minimal confidence for issues, default is 0.8 776 min-confidence: 0.8 777 gomnd: 778 settings: 779 mnd: 780 # the list of enabled checks, see https://github.com/tommy-muehle/go-mnd/#checks for description. 781 checks: argument,case,condition,operation,return,assign 782 gomodguard: 783 allowed: 784 modules: # List of allowed modules 785 # - gopkg.in/yaml.v2 786 domains: # List of allowed module domains 787 # - golang.org 788 blocked: 789 modules: # List of blocked modules 790 # - github.com/uudashr/go-module: # Blocked module 791 # recommendations: # Recommended modules that should be used instead (Optional) 792 # - golang.org/x/mod 793 # reason: "`mod` is the official go.mod parser library." # Reason why the recommended module should be used (Optional) 794 govet: 795 # report about shadowed variables 796 check-shadowing: true 797 798 # settings per analyzer 799 settings: 800 printf: # analyzer name, run `go tool vet help` to see all analyzers 801 funcs: # run `go tool vet help printf` to see available settings for `printf` analyzer 802 - (github.com/golangci/golangci-lint/pkg/logutils.Log).Infof 803 - (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf 804 - (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf 805 - (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf 806 807 # enable or disable analyzers by name 808 enable: 809 - atomicalign 810 enable-all: false 811 disable: 812 - shadow 813 disable-all: false 814 depguard: 815 list-type: blacklist 816 include-go-root: false 817 packages: 818 - github.com/sirupsen/logrus 819 packages-with-error-message: 820 # specify an error message to output when a blacklisted package is used 821 - github.com/sirupsen/logrus: "logging is allowed only by logutils.Log" 822 lll: 823 # max line length, lines longer will be reported. Default is 120. 824 # '\t' is counted as 1 character by default, and can be changed with the tab-width option 825 line-length: 120 826 # tab width in spaces. Default to 1. 827 tab-width: 1 828 maligned: 829 # print struct with more effective memory layout or not, false by default 830 suggest-new: true 831 misspell: 832 # Correct spellings using locale preferences for US or UK. 833 # Default is to use a neutral variety of English. 834 # Setting locale to US will correct the British spelling of 'colour' to 'color'. 835 locale: US 836 ignore-words: 837 - someword 838 nakedret: 839 # make an issue if func has more lines of code than this setting and it has naked returns; default is 30 840 max-func-lines: 30 841 prealloc: 842 # XXX: we don't recommend using this linter before doing performance profiling. 843 # For most programs usage of prealloc will be a premature optimization. 844 845 # Report preallocation suggestions only on simple loops that have no returns/breaks/continues/gotos in them. 846 # True by default. 847 simple: true 848 range-loops: true # Report preallocation suggestions on range loops, true by default 849 for-loops: false # Report preallocation suggestions on for loops, false by default 850 nolintlint: 851 # Enable to ensure that nolint directives are all used. Default is true. 852 allow-unused: false 853 # Disable to ensure that nolint directives don't have a leading space. Default is true. 854 allow-leading-space: true 855 # Exclude following linters from requiring an explanation. Default is []. 856 allow-no-explanation: [] 857 # Enable to require an explanation after each nolint directive. Default is false. 858 require-explanation: true 859 # Enable to require an explanation after each nolint directive. Default is false. 860 require-specific: true 861 rowserrcheck: 862 packages: 863 - github.com/jmoiron/sqlx 864 testpackage: 865 # regexp pattern to skip files 866 skip-regexp: (export|internal)_test\.go 867 unparam: 868 # Inspect exported functions, default is false. Set to true if no external program/library imports your code. 869 # XXX: if you enable this setting, unparam will report a lot of false-positives in text editors: 870 # if it's called for subdir of a project it can't find external interfaces. All text editor integrations 871 # with golangci-lint call it on a directory with the changed file. 872 check-exported: false 873 unused: 874 # treat code as a program (not a library) and report unused exported identifiers; default is false. 875 # XXX: if you enable this setting, unused will report a lot of false-positives in text editors: 876 # if it's called for subdir of a project it can't find funcs usages. All text editor integrations 877 # with golangci-lint call it on a directory with the changed file. 878 check-exported: false 879 whitespace: 880 multi-if: false # Enforces newlines (or comments) after every multi-line if statement 881 multi-func: false # Enforces newlines (or comments) after every multi-line function signature 882 wsl: 883 # If true append is only allowed to be cuddled if appending value is 884 # matching variables, fields or types on line above. Default is true. 885 strict-append: true 886 # Allow calls and assignments to be cuddled as long as the lines have any 887 # matching variables, fields or types. Default is true. 888 allow-assign-and-call: true 889 # Allow multiline assignments to be cuddled. Default is true. 890 allow-multiline-assign: true 891 # Allow declarations (var) to be cuddled. 892 allow-cuddle-declarations: false 893 # Allow trailing comments in ending of blocks 894 allow-trailing-comment: false 895 # Force newlines in end of case at this limit (0 = never). 896 force-case-trailing-whitespace: 0 897 # Force cuddling of err checks with err var assignment 898 force-err-cuddling: false 899 # Allow leading comments to be separated with empty liens 900 allow-separated-leading-comment: false 901 902 # The custom section can be used to define linter plugins to be loaded at runtime. See README doc 903 # for more info. 904 custom: 905 # Each custom linter should have a unique name. 906 example: 907 # The path to the plugin *.so. Can be absolute or local. Required for each custom linter 908 path: /path/to/example.so 909 # The description of the linter. Optional, just for documentation purposes. 910 description: This is an example usage of a plugin linter. 911 # Intended to point to the repo location of the linter. Optional, just for documentation purposes. 912 original-url: github.com/golangci/example-linter 913 914 linters: 915 enable: 916 - megacheck 917 - govet 918 disable: 919 - maligned 920 - prealloc 921 disable-all: false 922 presets: 923 - bugs 924 - unused 925 fast: false 926 927 928 issues: 929 # List of regexps of issue texts to exclude, empty list by default. 930 # But independently from this option we use default exclude patterns, 931 # it can be disabled by `exclude-use-default: false`. To list all 932 # excluded by default patterns execute `golangci-lint run --help` 933 exclude: 934 - abcdef 935 936 # Excluding configuration per-path, per-linter, per-text and per-source 937 exclude-rules: 938 # Exclude some linters from running on tests files. 939 - path: _test\.go 940 linters: 941 - gocyclo 942 - errcheck 943 - dupl 944 - gosec 945 946 # Exclude known linters from partially hard-vendored code, 947 # which is impossible to exclude via "nolint" comments. 948 - path: internal/hmac/ 949 text: "weak cryptographic primitive" 950 linters: 951 - gosec 952 953 # Exclude some staticcheck messages 954 - linters: 955 - staticcheck 956 text: "SA9003:" 957 958 # Exclude lll issues for long lines with go:generate 959 - linters: 960 - lll 961 source: "^//go:generate " 962 963 # Independently from option `exclude` we use default exclude patterns, 964 # it can be disabled by this option. To list all 965 # excluded by default patterns execute `golangci-lint run --help`. 966 # Default value for this option is true. 967 exclude-use-default: false 968 969 # The default value is false. If set to true exclude and exclude-rules 970 # regular expressions become case sensitive. 971 exclude-case-sensitive: false 972 973 # The list of ids of default excludes to include or disable. By default it's empty. 974 include: 975 - EXC0002 # disable excluding of issues about comments from golint 976 977 # Maximum issues count per one linter. Set to 0 to disable. Default is 50. 978 max-issues-per-linter: 0 979 980 # Maximum count of issues with the same text. Set to 0 to disable. Default is 3. 981 max-same-issues: 0 982 983 # Show only new issues: if there are unstaged changes or untracked files, 984 # only those changes are analyzed, else only changes in HEAD~ are analyzed. 985 # It's a super-useful option for integration of golangci-lint into existing 986 # large codebase. It's not practical to fix all existing issues at the moment 987 # of integration: much better don't allow issues in new code. 988 # Default is false. 989 new: false 990 991 # Show only new issues created after git revision `REV` 992 new-from-rev: REV 993 994 # Show only new issues created in git patch with set file path. 995 new-from-patch: path/to/patch/file 996 ``` 997 998 It's a [.golangci.yml](https://github.com/golangci/golangci-lint/blob/master/.golangci.yml) config file of this repo: we enable more linters 999 than the default and have more strict settings: 1000 1001 ```yaml 1002 linters-settings: 1003 depguard: 1004 list-type: blacklist 1005 packages: 1006 # logging is allowed only by logutils.Log, logrus 1007 # is allowed to use only in logutils package 1008 - github.com/sirupsen/logrus 1009 packages-with-error-message: 1010 - github.com/sirupsen/logrus: "logging is allowed only by logutils.Log" 1011 dupl: 1012 threshold: 100 1013 funlen: 1014 lines: 100 1015 statements: 50 1016 goconst: 1017 min-len: 2 1018 min-occurrences: 2 1019 gocritic: 1020 enabled-tags: 1021 - diagnostic 1022 - experimental 1023 - opinionated 1024 - performance 1025 - style 1026 disabled-checks: 1027 - dupImport # https://github.com/go-critic/go-critic/issues/845 1028 - ifElseChain 1029 - octalLiteral 1030 - whyNoLint 1031 - wrapperFunc 1032 gocyclo: 1033 min-complexity: 15 1034 goimports: 1035 local-prefixes: github.com/golangci/golangci-lint 1036 golint: 1037 min-confidence: 0 1038 gomnd: 1039 settings: 1040 mnd: 1041 # don't include the "operation" and "assign" 1042 checks: argument,case,condition,return 1043 govet: 1044 check-shadowing: true 1045 settings: 1046 printf: 1047 funcs: 1048 - (github.com/golangci/golangci-lint/pkg/logutils.Log).Infof 1049 - (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf 1050 - (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf 1051 - (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf 1052 lll: 1053 line-length: 140 1054 maligned: 1055 suggest-new: true 1056 misspell: 1057 locale: US 1058 nolintlint: 1059 allow-leading-space: true # don't require machine-readable nolint directives (i.e. with no leading space) 1060 allow-unused: false # report any unused nolint directives 1061 require-explanation: false # don't require an explanation for nolint directives 1062 require-specific: false # don't require nolint directives to be specific about which linter is being skipped 1063 1064 linters: 1065 # please, do not use `enable-all`: it's deprecated and will be removed soon. 1066 # inverted configuration with `enable-all` and `disable` is not scalable during updates of golangci-lint 1067 disable-all: true 1068 enable: 1069 - bodyclose 1070 - deadcode 1071 - depguard 1072 - dogsled 1073 - dupl 1074 - errcheck 1075 - funlen 1076 - gochecknoinits 1077 - goconst 1078 - gocritic 1079 - gocyclo 1080 - gofmt 1081 - goimports 1082 - golint 1083 - gomnd 1084 - goprintffuncname 1085 - gosec 1086 - gosimple 1087 - govet 1088 - ineffassign 1089 - interfacer 1090 - lll 1091 - misspell 1092 - nakedret 1093 - nolintlint 1094 - rowserrcheck 1095 - scopelint 1096 - staticcheck 1097 - structcheck 1098 - stylecheck 1099 - typecheck 1100 - unconvert 1101 - unparam 1102 - unused 1103 - varcheck 1104 - whitespace 1105 1106 # don't enable: 1107 # - gochecknoglobals 1108 # - gocognit 1109 # - godox 1110 # - maligned 1111 # - prealloc 1112 1113 issues: 1114 # Excluding configuration per-path, per-linter, per-text and per-source 1115 exclude-rules: 1116 - path: _test\.go 1117 linters: 1118 - gomnd 1119 1120 run: 1121 skip-dirs: 1122 - test/testdata_etc 1123 - internal/cache 1124 - internal/renameio 1125 - internal/robustio 1126 1127 # golangci.com configuration 1128 # https://github.com/golangci/golangci/wiki/Configuration 1129 service: 1130 golangci-lint-version: 1.23.x # use the fixed version to not introduce new linters unexpectedly 1131 prepare: 1132 - echo "here I can run custom commands, but no preparation needed for this repo" 1133 ``` 1134 1135 ## Custom Linters 1136 Some people and organizations may choose to have custom made linters run as a part of golangci-lint. That functionality 1137 is supported through go's plugin library. 1138 1139 ### Create a Copy of `golangci-lint` that Can Run with Plugins 1140 In order to use plugins, you'll need a golangci-lint executable that can run them. The normal version of this project 1141 is built with the vendors option, which breaks plugins that have overlapping dependencies. 1142 1143 1. Download [golangci-lint](https://github.com/golangci/golangci-lint) source code 1144 2. From the projects root directory, run `make vendor_free_build` 1145 3. Copy the `golangci-lint` executable that was created to your path, project, or other location 1146 1147 ### Configure Your Project for Linting 1148 If you already have a linter plugin available, you can follow these steps to define it's usage in a projects 1149 `.golangci.yml` file. An example linter can be found at [here](https://github.com/golangci/example-plugin-linter). If you're looking for 1150 instructions on how to configure your own custom linter, they can be found further down. 1151 1152 1. If the project you want to lint does not have one already, copy the [.golangci.yml](https://github.com/golangci/golangci-lint/blob/master/.golangci.yml) to the root directory. 1153 2. Adjust the yaml to appropriate `linters-settings:custom` entries as so: 1154 ``` 1155 linters-settings: 1156 custom: 1157 example: 1158 path: /example.so 1159 description: The description of the linter 1160 original-url: github.com/golangci/example-linter 1161 ``` 1162 1163 That is all the configuration that is required to run a custom linter in your project. Custom linters are enabled by default, 1164 but abide by the same rules as other linters. If the disable all option is specified either on command line or in 1165 `.golangci.yml` files `linters:disable-all: true`, custom linters will be disabled; they can be re-enabled by adding them 1166 to the `linters:enable` list, or providing the enabled option on the command line, `golangci-lint run -Eexample`. 1167 1168 ### To Create Your Own Custom Linter 1169 1170 Your linter must implement one or more `golang.org/x/tools/go/analysis.Analyzer` structs. 1171 Your project should also use `go.mod`. All versions of libraries that overlap `golangci-lint` (including replaced 1172 libraries) MUST be set to the same version as `golangci-lint`. You can see the versions by running `go version -m golangci-lint`. 1173 1174 You'll also need to create a go file like `plugin/example.go`. This MUST be in the package `main`, and define a 1175 variable of name `AnalyzerPlugin`. The `AnalyzerPlugin` instance MUST implement the following interface: 1176 ``` 1177 type AnalyzerPlugin interface { 1178 GetAnalyzers() []*analysis.Analyzer 1179 } 1180 ``` 1181 The type of `AnalyzerPlugin` is not important, but is by convention `type analyzerPlugin struct {}`. See 1182 [plugin/example.go](https://github.com/golangci/example-plugin-linter/plugin/example.go) for more info. 1183 1184 To build the plugin, from the root project directory, run `go build -buildmode=plugin plugin/example.go`. This will create a plugin `*.so` 1185 file that can be copied into your project or another well known location for usage in golangci-lint. 1186 1187 ## False Positives 1188 1189 False positives are inevitable, but we did our best to reduce their count. For example, we have a default enabled set of [exclude patterns](#command-line-options). If a false positive occurred you have the following choices: 1190 1191 1. Exclude issue by text using command-line option `-e` or config option `issues.exclude`. It's helpful when you decided to ignore all issues of this type. Also, you can use `issues.exclude-rules` config option for per-path or per-linter configuration. 1192 2. Exclude this one issue by using special comment `//nolint` (see [the section](#nolint) below). 1193 3. Exclude issues in path by `run.skip-dirs`, `run.skip-files` or `issues.exclude-rules` config options. 1194 1195 Please create [GitHub Issues here](https://github.com/golangci/golangci-lint/issues/new) if you find any false positives. We will add it to the default exclude list if it's common or we will fix underlying linter. 1196 1197 ### Nolint 1198 1199 To exclude issues from all linters use `//nolint`. For example, if it's used inline (not from the beginning of the line) it excludes issues only for this line. 1200 1201 ```go 1202 var bad_name int //nolint 1203 ``` 1204 1205 To exclude issues from specific linters only: 1206 1207 ```go 1208 var bad_name int //nolint:golint,unused 1209 ``` 1210 1211 To exclude issues for the block of code use this directive on the beginning of a line: 1212 1213 ```go 1214 //nolint 1215 func allIssuesInThisFunctionAreExcluded() *string { 1216 // ... 1217 } 1218 1219 //nolint:govet 1220 var ( 1221 a int 1222 b int 1223 ) 1224 ``` 1225 1226 Also, you can exclude all issues in a file by: 1227 1228 ```go 1229 //nolint:unparam 1230 package pkg 1231 ``` 1232 1233 You may add a comment explaining or justifying why `//nolint` is being used on the same line as the flag itself: 1234 1235 ```go 1236 //nolint:gocyclo // This legacy function is complex but the team too busy to simplify it 1237 func someLegacyFunction() *string { 1238 // ... 1239 } 1240 ``` 1241 1242 You can see more examples of using `//nolint` in [our tests](https://github.com/golangci/golangci-lint/tree/master/pkg/result/processors/testdata) for it. 1243 1244 Use `//nolint` instead of `// nolint` because machine-readable comments should have no space by Go convention. 1245 1246 ## FAQ 1247 1248 **How do you add a custom linter?** 1249 1250 You can integrate it yourself, see this [wiki page](https://github.com/golangci/golangci-lint/wiki/How-to-add-a-custom-linter) with documentation. Or you can create a [GitHub Issue](https://github.com/golangci/golangci-lint/issues/new) and we will integrate when time permits. 1251 1252 **It's cool to use `golangci-lint` when starting a project, but what about existing projects with large codebase? It will take days to fix all found issues** 1253 1254 We are sure that every project can easily integrate `golangci-lint`, even the large one. The idea is to not fix all existing issues. Fix only newly added issue: issues in new code. To do this setup CI (or better use [GolangCI](https://golangci.com)) to run `golangci-lint` with option `--new-from-rev=HEAD~1`. Also, take a look at option `--new`, but consider that CI scripts that generate unstaged files will make `--new` only point out issues in those files and not in the last commit. In that regard `--new-from-rev=HEAD~1` is safer. 1255 By doing this you won't create new issues in your code and can choose fix existing issues (or not). 1256 1257 **How to use `golangci-lint` in CI (Continuous Integration)?** 1258 1259 You have 2 choices: 1260 1261 1. Use [GolangCI](https://golangci.com): this service is highly integrated with GitHub (issues are commented in the pull request) and uses a `golangci-lint` tool. For configuration use `.golangci.yml` (or toml/json). 1262 2. Use custom CI: just run `golangci-lint` in CI and check the exit code. If it's non-zero - fail the build. The main disadvantage is that you can't see issues in pull request code and would need to view the build log, then open the referenced source file to see the context. 1263 1264 We don't recommend vendoring `golangci-lint` in your repo: you will get troubles updating `golangci-lint`. Please, use recommended way to install with the shell script: it's very fast. 1265 1266 **Do I need to run `go install`?** 1267 1268 No, you don't need to do it anymore. 1269 1270 **Which go versions are supported** 1271 Short answer: go 1.12 and newer are officially supported. 1272 1273 Long answer: 1274 1275 1. go < 1.9 isn't supported 1276 2. go1.9 is officially supported by golangci-lint <= v1.10.2 1277 3. go1.10 is officially supported by golangci-lint <= 1.15.0. 1278 4. go1.11 is officially supported by golangci-lint <= 1.17.1. 1279 5. go1.12+ are officially supported by the latest version of golangci-lint (>= 1.18.0). 1280 1281 **`golangci-lint` doesn't work** 1282 1283 1. Please, ensure you are using the latest binary release. 1284 2. Run it with `-v` option and check the output. 1285 3. If it doesn't help create a [GitHub issue](https://github.com/golangci/golangci-lint/issues/new) with the output from the error and #2 above. 1286 1287 **Why running with `--fast` is slow on the first run?** 1288 Because the first run caches type information. All subsequent runs will be fast. 1289 Usually this options is used during development on local machine and compilation was already performed. 1290 1291 ## Thanks 1292 1293 Thanks to all [contributors](https://github.com/golangci/golangci-lint/graphs/contributors)! 1294 Thanks to [alecthomas/gometalinter](https://github.com/alecthomas/gometalinter) for inspiration and amazing work. 1295 Thanks to [bradleyfalzon/revgrep](https://github.com/bradleyfalzon/revgrep) for cool diff tool. 1296 1297 Thanks to developers and authors of used linters: 1298 - [timakin](https://github.com/timakin) 1299 - [kisielk](https://github.com/kisielk) 1300 - [golang](https://github.com/golang) 1301 - [jingyugao](https://github.com/jingyugao) 1302 - [dominikh](https://github.com/dominikh) 1303 - [securego](https://github.com/securego) 1304 - [opennota](https://github.com/opennota) 1305 - [mvdan](https://github.com/mvdan) 1306 - [mdempsky](https://github.com/mdempsky) 1307 - [gordonklaus](https://github.com/gordonklaus) 1308 - [mibk](https://github.com/mibk) 1309 - [jgautheron](https://github.com/jgautheron) 1310 - [remyoudompheng](https://github.com/remyoudompheng) 1311 - [alecthomas](https://github.com/alecthomas) 1312 - [uudashr](https://github.com/uudashr) 1313 - [tdakkota](https://github.com/tdakkota) 1314 - [OpenPeeDeeP](https://github.com/OpenPeeDeeP) 1315 - [client9](https://github.com/client9) 1316 - [walle](https://github.com/walle) 1317 - [alexkohler](https://github.com/alexkohler) 1318 - [kyoh86](https://github.com/kyoh86) 1319 - [go-critic](https://github.com/go-critic) 1320 - [leighmcculloch](https://github.com/leighmcculloch) 1321 - [matoous](https://github.com/matoous) 1322 - [ultraware](https://github.com/ultraware) 1323 - [bombsimon](https://github.com/bombsimon) 1324 - [jirfag](https://github.com/jirfag) 1325 - [tommy-muehle](https://github.com/tommy-muehle) 1326 - [Djarvur](https://github.com/Djarvur) 1327 - [ryancurrah](https://github.com/ryancurrah) 1328 - [tetafro](https://github.com/tetafro) 1329 - [maratori](https://github.com/maratori) 1330 - [nakabonne](https://github.com/nakabonne) 1331 - [golangci-lint](https://github.com/golangci-lint) 1332 1333 ## Changelog 1334 1335 Follow the news and releases on our [twitter](https://twitter.com/golangci) and our [blog](https://medium.com/golangci). 1336 There is the most valuable changes log: 1337 1338 ### May 2020 1339 1. Add new linters: `nolintlint`, `goerr113` 1340 2. Updated linters: `godot` 1341 1342 ### April 2020 1343 1344 1. Add new linters: `testpackage`, `nestif`, `godot`, `gomodguard`, `asciicheck` 1345 2. Add github actions output format 1346 3. Update linters: `wsl`, `gomodguard`, `gosec` 1347 4. Support `disabled-tags` setting for `gocritic` 1348 5. Mitigate OOM and "failed prerequisites" 1349 6. Self-isolate due to unexpected pandemics 1350 7. Support case-sensitive excludes 1351 8. Allow granular re-enabling excludes by ID, e.g. `EXC0002` 1352 1353 ### September 2019 1354 1355 1. Support go1.13 1356 2. Add new linters: `funlen`, `whitespace` (with auto-fix) and `godox` 1357 3. Update linters: `gochecknoglobals`, `scopelint`, `gosec` 1358 4. Provide pre-built binary for ARM and FreeBSD 1359 5. 2. Fix false-positives in `unused` 1360 6. Support `--skip-dirs-use-default` 1361 7. Add support for bash completions 1362 1363 ### July 2019 1364 1365 1. Fix parallel writes race condition 1366 2. Update bodyclose with fixed panic 1367 1368 ### June 2019 1369 1370 1. Treat Go source files as a plain text by `misspell`: it allows detecting issues in strings, variable names, etc. 1371 2. Implement richer and more stable auto-fix of `misspell` issues. 1372 1373 ### May 2019 1374 1375 1. Add [bodyclose](https://github.com/timakin/bodyclose) linter. 1376 2. Support junit-xml output. 1377 1378 ### April 2019 1379 1380 1. Update go-critic, new checkers were added: badCall, dupImports, evalOrder, newDeref 1381 2. Fix staticcheck panic on packages that do not compile 1382 3. Make install script work on Windows 1383 4. Fix compatibility with the latest x/tools version and update golang.org/x/tools 1384 5. Correct import path of module sourcegraph/go-diff 1385 6. Fix `max-issues-per-linter` name 1386 7. Fix linting of preprocessed files (e.g. `*.qtpl.go`, goyacc) 1387 8. Enable auto-fixing when running via pre-commit 1388 1389 ### March 2019 1390 1391 1. Support the newest `go vet` (with `go/analysis`) 1392 2. Support configuration of `go vet`: e.g. you can set print functions by `linters-settings.govet.settings.printf.funcs` 1393 3. Update megacheck (staticcheck) to 2019.1.1 1394 4. Add [information](https://github.com/golangci/golangci-lint#memory-usage-of-golangci-lint) about controlling space-time trade-off into README 1395 5. Exclude issues by source code line regexp by `issues.exclude-rules[i].source` 1396 6. Build and test on go 1.12 1397 7. Support `--color` option 1398 8. Update x/tools to fix c++ issues 1399 9. Include support for log level 1400 10. Sort linters list in help commands 1401 1402 ## Debug 1403 1404 You can see a verbose output of linter by using `-v` option. 1405 1406 If you would like to see more detailed logs you can set environment variable `GL_DEBUG` to debug `golangci-lint`. 1407 It's value is a list of debug tags. For example, `GL_DEBUG=loader,gocritic golangci-lint run`. 1408 Existing debug tags: 1409 1410 1. `gocritic` - debug `go-critic` linter; 1411 2. `env` - debug `go env` command; 1412 3. `loader` - debug packages loading (including `go/packages` internal debugging); 1413 4. `autogen_exclude` - debug a filter excluding autogenerated source code; 1414 5. `nolint` - debug a filter excluding issues by `//nolint` comments. 1415 1416 ## Future Plans 1417 1418 1. Upstream all changes of forked linters. 1419 2. Make it easy to write own linter/checker: it should take a minimum code, have perfect documentation, debugging and testing tooling. 1420 3. Speed up SSA loading: on-disk cache and existing code profiling-optimizing. 1421 4. Analyze (don't only filter) only new code: analyze only changed files and dependencies, make incremental analysis, caches. 1422 5. Smart new issues detector: don't print existing issues on changed lines. 1423 6. Minimize false-positives by fixing linters and improving testing tooling. 1424 7. Automatic issues fixing (code rewrite, refactoring) where it's possible. 1425 8. Documentation for every issue type. 1426 1427 ## Contact Information 1428 1429 Slack channel: [#golangci-lint](https://slack.com/share/IS0TDK8RG/TEKQWjTZXxfK9Ta2G5HrnsMY/enQtODg0OTMxNjU0ODY2LWUyMTQ3NDc2MmNlNGU3NTNhYWE0Nzc3MjUyZjkxZWI3YjI5ODMwNDA1NTU3MmM2Yzc5ZjQyYTFkNThlODllN2Y). 1430 1431 You can contact the [author](https://github.com/jirfag) of GolangCI-Lint 1432 by [denis@golangci.com](mailto:denis@golangci.com). Follow the news and releases on our [twitter](https://twitter.com/golangci) and our [blog](https://medium.com/golangci). 1433 1434 ## License Scan 1435 1436 [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fgolangci%2Fgolangci-lint.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fgolangci%2Fgolangci-lint?ref=badge_large)