github.com/slixurd/golangci-lint@v1.10.1/README.md (about) 1 # GolangCI-Lint 2 [![Build Status](https://travis-ci.com/golangci/golangci-lint.svg?branch=master)](https://travis-ci.com/golangci/golangci-lint) 3 4 GolangCI-Lint is a linters aggregator. It's fast: on average [5 times faster](#performance) than gometalinter. 5 It's [easy to integrate and use](#command-line-options), has [nice output](#quick-start) and has a minimum number of false positives. 6 7 GolangCI-Lint has [integrations](#editor-integration) with VS Code, GNU Emacs, Sublime Text. 8 9 Sponsored by [GolangCI.com](https://golangci.com): SaaS service for running linters on Github pull requests. Free for Open Source. 10 11 <a href="https://golangci.com/"><img src="docs/go.png" width="250px"></a> 12 13 * [Demo](#demo) 14 * [Install](#install) 15 * [Quick Start](#quick-start) 16 * [Editor Integration](#editor-integration) 17 * [Comparison](#comparison) 18 * [Performance](#performance) 19 * [Internals](#internals) 20 * [Trusted By](#trusted-by) 21 * [Supported Linters](#supported-linters) 22 * [Configuration](#configuration) 23 * [False Positives](#false-positives) 24 * [FAQ](#faq) 25 * [Thanks](#thanks) 26 * [Future Plans](#future-plans) 27 * [Changelog](#changelog) 28 * [Contact Information](#contact-information) 29 30 # Demo 31 <p align="center"> 32 <img src="./docs/demo.svg" width="100%"> 33 </p> 34 35 Short 1.5 min video demo of analyzing [beego](https://github.com/astaxie/beego). 36 [![asciicast](https://asciinema.org/a/183662.png)](https://asciinema.org/a/183662) 37 38 # Install 39 ## CI Installation 40 Most installations are done for CI (travis, circleci etc). It's important to have reproducible CI: 41 don't start to fail all builds at the same time. With golangci-lint this can happen if you 42 use `--enable-all` and a new linter is added or even without `--enable-all`: when one upstream linter 43 is upgraded. 44 45 It's highly recommended to install a fixed version of golangci-lint. 46 Releases are available on the [releases page](https://github.com/golangci/golangci-lint/releases). 47 48 The recommended way to install golangci-lint (replace `vX.Y.Z` with the latest 49 version from the [releases page](https://github.com/golangci/golangci-lint/releases)): 50 ```bash 51 # binary will be $GOPATH/bin/golangci-lint 52 curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | bash -s -- -b $GOPATH/bin vX.Y.Z 53 54 # or install it into ./bin/ 55 # curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | bash -s vX.Y.Z 56 57 # golangci-lint --version 58 ``` 59 60 Periodically update version of golangci-lint: the project is under active development 61 and is constantly being improved. But please always check for newly found issues and 62 update if needed. 63 64 ## Local Installation 65 It's a not recommended for your CI pipeline. Only install like this for your local development environment. 66 ```bash 67 go get -u github.com/golangci/golangci-lint/cmd/golangci-lint 68 ``` 69 70 You can also install it on OSX using brew: 71 ```bash 72 brew install golangci/tap/golangci-lint 73 brew upgrade golangci/tap/golangci-lint 74 ``` 75 76 # Quick Start 77 To run golangci-lint execute: 78 ```bash 79 golangci-lint run 80 ``` 81 82 It's an equivalent of executing: 83 ```bash 84 golangci-lint run ./... 85 ``` 86 87 You can choose which directories and files to analyze: 88 ```bash 89 golangci-lint run dir1 dir2/... dir3/file1.go 90 ``` 91 Directories are NOT analyzed recursively. To analyze them recursively append `/...` to their path. 92 93 GolangCI-Lint can be used with zero configuration. By default the following linters are enabled: 94 ``` 95 $ golangci-lint help linters 96 Enabled by default linters: 97 govet: Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string [fast: false] 98 errcheck: Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases [fast: false] 99 staticcheck: Staticcheck is a go vet on steroids, applying a ton of static analysis checks [fast: false] 100 unused: Checks Go code for unused constants, variables, functions and types [fast: false] 101 gosimple: Linter for Go source code that specializes in simplifying a code [fast: false] 102 structcheck: Finds an unused struct fields [fast: false] 103 varcheck: Finds unused global variables and constants [fast: false] 104 ineffassign: Detects when assignments to existing variables are not used [fast: true] 105 deadcode: Finds unused code [fast: false] 106 typecheck: Like the front-end of a Go compiler, parses and type-checks Go code [fast: false] 107 ``` 108 109 and the following linters are disabled by default: 110 ``` 111 $ golangci-lint help linters 112 ... 113 Disabled by default linters: 114 golint: Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes [fast: true] 115 gas: Inspects source code for security problems [fast: false] 116 interfacer: Linter that suggests narrower interface types [fast: false] 117 unconvert: Remove unnecessary type conversions [fast: false] 118 dupl: Tool for code clone detection [fast: true] 119 goconst: Finds repeated strings that could be replaced by a constant [fast: true] 120 gocyclo: Computes and checks the cyclomatic complexity of functions [fast: true] 121 gofmt: Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification [fast: true] 122 goimports: Goimports does everything that gofmt does. Additionally it checks unused imports [fast: true] 123 maligned: Tool to detect Go structs that would take less memory if their fields were sorted [fast: false] 124 megacheck: 3 sub-linters in one: unused, gosimple and staticcheck [fast: false] 125 depguard: Go linter that checks if package imports are in a list of acceptable packages [fast: false] 126 misspell: Finds commonly misspelled English words in comments [fast: true] 127 lll: Reports long lines [fast: true] 128 unparam: Reports unused function parameters [fast: false] 129 nakedret: Finds naked returns in functions greater than a specified function length [fast: true] 130 prealloc: Finds slice declarations that could potentially be preallocated [fast: true] 131 ``` 132 133 Pass `-E/--enable` to enable linter and `-D/--disable` to disable: 134 ```bash 135 $ golangci-lint run --disable-all -E errcheck 136 ``` 137 138 # Editor Integration 139 1. [Go for Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=ms-vscode.Go). 140 2. Sublime Text - [plugin](https://github.com/alecthomas/SublimeLinter-contrib-golang-cilint) for SublimeLinter. 141 3. GoLand 142 - Configure [File Watcher](https://www.jetbrains.com/help/go/settings-tools-file-watchers.html) with arguments `run --print-issued-lines=false $FileDir$`. 143 - Predefined File Watcher will be added in [issue](https://youtrack.jetbrains.com/issue/GO-4574). 144 4. GNU Emacs 145 - [Spacemacs](https://github.com/syl20bnr/spacemacs/blob/develop/layers/+lang/go/README.org#pre-requisites) 146 - [flycheck checker](https://github.com/weijiangan/flycheck-golangci-lint). 147 5. Vim 148 - vim-go open [issue](https://github.com/fatih/vim-go/issues/1841) 149 - syntastic [merged pull request](https://github.com/vim-syntastic/syntastic/pull/2190) with golangci-lint support 150 151 # Comparison 152 ## `golangci-lint` vs `gometalinter` 153 GolangCI-Lint was created to fix the following issues with `gometalinter`: 154 1. Slow work: `gometalinter` usually works for minutes in average projects. 155 **GolangCI-Lint works [2-7x times faster](#performance)** by [reusing work](#internals). 156 2. Huge memory consumption: parallel linters don't share the same program representation and can consume 157 `n` times more memory (`n` - concurrency). GolangCI-Lint fixes it by sharing representation and **consumes 26% less memory**. 158 3. Doesn't use real bounded concurrency: if you set it to `n` it can take up to `n*n` threads because of 159 forced threads in specific linters. `gometalinter` can't do anything about it because it runs linters as 160 black boxes in forked processes. In GolangCI-Lint we run all linters in one process and completely control 161 them. Configured concurrency will be correctly bounded. 162 This issue is important because you often want to set concurrency to the CPUs count minus one to 163 ensure you **do not freeze your PC** and be able to work on it while analyzing code. 164 4. Lack of nice output. We like how the `gcc` and `clang` compilers format their warnings: **using colors, 165 printing warning lines and showing the position in line**. 166 5. Too many issues. GolangCI-Lint cuts a lot of issues by using default exclude list of common false-positives. 167 By default, it has enabled **smart issues processing**: merge multiple issues for one line, merge issues with the 168 same text or from the same linter. All of these smart processors can be configured by the user. 169 6. Integration into large codebases. A good way to start using linters in a large project is not to fix a plethora 170 of existing issues, but to set up CI and **fix only issues in new commits**. You can use `revgrep` for it, but it's 171 yet another utility to install and configure. With `golangci-lint` it's much easier: `revgrep` is already built into 172 `golangci-lint` and you can use it with one option (`-n, --new` or `--new-from-rev`). 173 7. Installation. With `gometalinter`, you need to run a linters installation step. It's easy to forget this step and 174 end up with stale linters. It also complicates CI setup. GolangCI-Lint requires **no installation of linters**. 175 8. **Yaml or toml config**. Gometalinter's JSON isn't convenient for config files. 176 177 ## `golangci-lint` vs Running Linters Manually 178 1. It will be much slower because `golangci-lint` runs all linters in parallel and shares 50-80% of linters work. 179 2. It will have less control and more false-positives: some linters can't be properly configured without hacks. 180 3. It will take more time because of different usages and need of tracking of versions of `n` linters. 181 182 # Performance 183 Benchmarks were executed on MacBook Pro (Retina, 13-inch, Late 2013), 2,4 GHz Intel Core i5, 8 GB 1600 MHz DDR3. 184 It has 4 cores and concurrent linting as a default consuming all cores. 185 Benchmark was run (and measured) automatically, see the code 186 [here](https://github.com/golangci/golangci-lint/blob/master/test/bench_test.go) (`BenchmarkWithGometalinter`). 187 188 We measure peak memory usage (RSS) by tracking of processes RSS every 5 ms. 189 190 ## Comparison with gometalinter 191 We compare golangci-lint and gometalinter in default mode, but explicitly enable all linters because of small differences in the default configuration. 192 ```bash 193 $ golangci-lint run --no-config --issues-exit-code=0 --deadline=30m \ 194 --disable-all --enable=deadcode --enable=gocyclo --enable=golint --enable=varcheck \ 195 --enable=structcheck --enable=maligned --enable=errcheck --enable=dupl --enable=ineffassign \ 196 --enable=interfacer --enable=unconvert --enable=goconst --enable=gas --enable=megacheck 197 $ gometalinter --deadline=30m --vendor --cyclo-over=30 --dupl-threshold=150 \ 198 --exclude=<defaul golangci-lint excludes> --skip=testdata --skip=builtin \ 199 --disable-all --enable=deadcode --enable=gocyclo --enable=golint --enable=varcheck \ 200 --enable=structcheck --enable=maligned --enable=errcheck --enable=dupl --enable=ineffassign \ 201 --enable=interfacer --enable=unconvert --enable=goconst --enable=gas --enable=megacheck 202 ./... 203 ``` 204 205 | Repository | GolangCI Time | GolangCI Is Faster than Gometalinter | GolangCI Memory | GolangCI eats less memory than Gometalinter | 206 | ---------- | ------------- | ------------------------------------ | --------------- | ------------------------------------------- | 207 | gometalinter repo, 4 kLoC | 6s | **6.4x** | 0.7GB | 33% | 208 | self-repo, 4 kLoC | 12s | **7.5x** | 1.2GB | 41% | 209 | beego, 50 kLoC | 10s | **4.2x** | 1.4GB | 9% | 210 | hugo, 70 kLoC | 15s | **6.1x** | 1.6GB | 44% | 211 | consul, 127 kLoC | 58s | **4x** | 2.7GB | 41% | 212 | terraform, 190 kLoC | 2m13s | **1.6x** | 4.8GB | 0% | 213 | go-ethereum, 250 kLoC | 33s | **5x** | 3.6GB | 0% | 214 | go source (`$GOROOT/src`), 1300 kLoC | 2m45s | **2x** | 4.7GB | 0% | 215 216 217 **On average golangci-lint is 4.6 times faster** than gometalinter. Maximum difference is in the 218 self-repo: **7.5 times faster**, minimum difference is in terraform source code repo: 1.8 times faster. 219 220 On average golangci-lint consumes 26% less memory. 221 222 ## Why golangci-lint is faster 223 224 Golangci-lint directly calls linters (no forking) and reuses 80% of work by parsing program only once. 225 Read [this section](#internals) for details. 226 227 # Internals 228 229 1. Work sharing 230 The key difference with gometalinter is that golangci-lint shares work between specific linters (golint, govet, ...). 231 We don't fork to call specific linter but use its API. 232 For small and medium projects 50-90% of work between linters can be reused. 233 * load `loader.Program` once 234 235 We load program (parsing all files and type-checking) only once for all linters. For the most of linters 236 it's the most heavy operation: it takes 5 seconds on 8 kLoC repo and 11 seconds on `$GOROOT/src`. 237 * build `ssa.Program` once 238 239 Some linters (megacheck, interfacer, unparam) work on SSA representation. 240 Building of this representation takes 1.5 seconds on 8 kLoC repo and 6 seconds on `$GOROOT/src`. 241 `SSA` representation is used from a [fork of go-tools](https://github.com/dominikh/go-tools), not the official one. 242 243 * parse source code and build AST once 244 245 Parsing one source file takes 200 us on average. Parsing of all files in `$GOROOT/src` takes 2 seconds. 246 Currently we parse each file more than once because it's not the bottleneck. But we already save a lot of 247 extra parsing. We're planning to parse each file only once. 248 249 * walk files and directories once 250 251 It takes 300-1000 ms for `$GOROOT/src`. 252 2. Smart linters scheduling 253 254 We schedule linters by a special algorithm which takes estimated execution time into account. It allows 255 to save 10-30% of time when one of heavy linters (megacheck etc) is enabled. 256 257 3. Improved program loading 258 259 We smartly use setting `TypeCheckFuncBodies` in `loader.Config` to build `loader.Program`. 260 If there are no linters requiring SSA enabled we can load dependencies of analyzed code much faster 261 by not analyzing their functions: we analyze only file-level declarations. It makes program loading 262 10-30% faster in such cases. 263 4. Don't fork to run shell commands 264 265 All linters are vendored in the `/vendor` folder: their version is fixed, they are builtin 266 and you don't need to install them separately. 267 268 # Trusted By 269 270 The following great projects use golangci-lint: 271 272 * [GoogleContainerTools/skaffold](https://github.com/GoogleContainerTools/skaffold/blob/master/hack/linter.sh#L24) - Easy and Repeatable Kubernetes Development 273 * [goreleaser/goreleaser](https://github.com/goreleaser/goreleaser/blob/master/Makefile#L47) - Deliver Go binaries as fast and easily as possible 274 * [goreleaser/nfpm](https://github.com/goreleaser/nfpm/blob/master/Makefile#L43) - NFPM is Not FPM - a simple deb and rpm packager written in Go 275 * [goreleaser/godownloader](https://github.com/goreleaser/godownloader/blob/master/Makefile#L37) - Download Go binaries as fast and easily as possible 276 * [asobti/kube-monkey](https://github.com/asobti/kube-monkey/blob/master/Makefile#L12) - An implementation of Netflix's Chaos Monkey for Kubernetes clusters 277 * [nutanix/terraform-provider-nutanix](https://github.com/nutanix/terraform-provider-nutanix/blob/develop/.golangci.yml) - Terraform Nutanix Provider 278 * [getantibody/antibody](https://github.com/getantibody/antibody/blob/master/Makefile#L32) - The fastest shell plugin manager 279 * [Aptomi/aptomi](https://github.com/Aptomi/aptomi/blob/master/.golangci.yml) - Application delivery engine for k8s 280 * [status-im/status-go](https://github.com/status-im/status-go/blob/develop/.golangci.yml) - The Status module that consumes go-ethereum 281 * [ovrclk/akash](https://github.com/ovrclk/akash/blob/master/.golangci.yaml) - Blockchain-powered decentralized compute platform 282 283 284 # Supported Linters 285 To see a list of supported linters and which linters are enabled/disabled: 286 ``` 287 golangci-lint help linters 288 ``` 289 290 ## Enabled By Default Linters 291 - [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 292 - [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 293 - [staticcheck](https://staticcheck.io/) - Staticcheck is a go vet on steroids, applying a ton of static analysis checks 294 - [unused](https://github.com/dominikh/go-tools/tree/master/cmd/unused) - Checks Go code for unused constants, variables, functions and types 295 - [gosimple](https://github.com/dominikh/go-tools/tree/master/cmd/gosimple) - Linter for Go source code that specializes in simplifying a code 296 - [structcheck](https://github.com/opennota/check) - Finds an unused struct fields 297 - [varcheck](https://github.com/opennota/check) - Finds unused global variables and constants 298 - [ineffassign](https://github.com/gordonklaus/ineffassign) - Detects when assignments to existing variables are not used 299 - [deadcode](https://github.com/remyoudompheng/go-misc/tree/master/deadcode) - Finds unused code 300 - typecheck - Like the front-end of a Go compiler, parses and type-checks Go code 301 302 ## Disabled By Default Linters (`-E/--enable`) 303 - [golint](https://github.com/golang/lint) - Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes 304 - [gas](https://github.com/GoASTScanner/gas) - Inspects source code for security problems 305 - [interfacer](https://github.com/mvdan/interfacer) - Linter that suggests narrower interface types 306 - [unconvert](https://github.com/mdempsky/unconvert) - Remove unnecessary type conversions 307 - [dupl](https://github.com/mibk/dupl) - Tool for code clone detection 308 - [goconst](https://github.com/jgautheron/goconst) - Finds repeated strings that could be replaced by a constant 309 - [gocyclo](https://github.com/alecthomas/gocyclo) - Computes and checks the cyclomatic complexity of functions 310 - [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 311 - [goimports](https://godoc.org/golang.org/x/tools/cmd/goimports) - Goimports does everything that gofmt does. Additionally it checks unused imports 312 - [maligned](https://github.com/mdempsky/maligned) - Tool to detect Go structs that would take less memory if their fields were sorted 313 - [megacheck](https://github.com/dominikh/go-tools/tree/master/cmd/megacheck) - 3 sub-linters in one: unused, gosimple and staticcheck 314 - [depguard](https://github.com/OpenPeeDeeP/depguard) - Go linter that checks if package imports are in a list of acceptable packages 315 - [misspell](https://github.com/client9/misspell) - Finds commonly misspelled English words in comments 316 - [lll](https://github.com/walle/lll) - Reports long lines 317 - [unparam](https://github.com/mvdan/unparam) - Reports unused function parameters 318 - [nakedret](https://github.com/alexkohler/nakedret) - Finds naked returns in functions greater than a specified function length 319 - [prealloc](https://github.com/alexkohler/prealloc) - Finds slice declarations that could potentially be preallocated 320 321 # Configuration 322 The config file has lower priority than command-line options. If the same bool/string/int option is provided on the command-line 323 and in the config file, the option from command-line will be used. 324 Slice options (e.g. list of enabled/disabled linters) are combined from the command-line and config file. 325 326 To see a list of enabled by your configuration linters: 327 ``` 328 golangci-lint linters 329 ``` 330 331 ## Command-Line Options 332 ``` 333 golangci-lint run -h 334 Usage: 335 golangci-lint run [flags] 336 337 Flags: 338 --out-format string Format of output: colored-line-number|line-number|json|tab|checkstyle (default "colored-line-number") 339 --print-issued-lines Print lines of code with issue (default true) 340 --print-linter-name Print linter name in issue line (default true) 341 --issues-exit-code int Exit code when issues were found (default 1) 342 --build-tags strings Build tags 343 --deadline duration Deadline for total work (default 1m0s) 344 --tests Analyze tests (*_test.go) (default true) 345 --print-resources-usage Print avg and max memory usage of golangci-lint and total time 346 -c, --config PATH Read config from file path PATH 347 --no-config Don't read config 348 --skip-dirs strings Regexps of directories to skip 349 --skip-files strings Regexps of files to skip 350 -E, --enable strings Enable specific linter 351 -D, --disable strings Disable specific linter 352 --enable-all Enable all linters 353 --disable-all Disable all linters 354 -p, --presets strings Enable presets (bugs|unused|format|style|complexity|performance) of linters. Run 'golangci-lint linters' to see them. This option implies option --disable-all 355 --fast Run only fast linters from enabled linters set 356 -e, --exclude strings Exclude issue by regexp 357 --exclude-use-default Use or not use default excludes: 358 # errcheck: Almost all programs ignore errors on these functions and in most cases it's ok 359 - Error return value of .((os\.)?std(out|err)\..*|.*Close|.*Flush|os\.Remove(All)?|.*printf?|os\.(Un)?Setenv). is not checked 360 361 # golint: Annoying issue about not having a comment. The rare codebase has such comments 362 - (comment on exported (method|function|type|const)|should have( a package)? comment|comment should be of the form) 363 364 # golint: False positive when tests are defined in package 'test' 365 - func name will be used as test\.Test.* by other packages, and that stutters; consider calling this 366 367 # gas: Too many false-positives on 'unsafe' usage 368 - Use of unsafe calls should be audited 369 370 # gas: Too many false-positives for parametrized shell calls 371 - Subprocess launch(ed with variable|ing should be audited) 372 373 # gas: Duplicated errcheck checks 374 - G104 375 376 # gas: Too many issues in popular repos 377 - (Expect directory permissions to be 0750 or less|Expect file permissions to be 0600 or less) 378 379 # gas: False positive is triggered by 'src, err := ioutil.ReadFile(filename)' 380 - Potential file inclusion via variable 381 382 # govet: Common false positives 383 - (possible misuse of unsafe.Pointer|should have signature) 384 385 # megacheck: Developers tend to write in C-style with an explicit 'break' in a 'switch', so it's ok to ignore 386 - ineffective break statement. Did you mean to break out of the outer loop 387 (default true) 388 --max-issues-per-linter int Maximum issues count per one linter. Set to 0 to disable (default 50) 389 --max-same-issues int Maximum count of issues with the same text. Set to 0 to disable (default 3) 390 -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. 391 It's a super-useful option for integration of golangci-lint into existing large codebase. 392 It's not practical to fix all existing issues at the moment of integration: much better to not allow issues in new code. 393 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. 394 --new-from-rev REV Show only new issues created after git revision REV 395 --new-from-patch PATH Show only new issues created in git patch with file path PATH 396 -h, --help help for run 397 398 Global Flags: 399 -j, --concurrency int Concurrency (default NumCPU) (default 8) 400 --cpu-profile-path string Path to CPU profile output file 401 --mem-profile-path string Path to memory profile output file 402 -v, --verbose verbose output 403 404 ``` 405 406 ## Config File 407 GolangCI-Lint looks for config files in the following paths from the current working directory: 408 - `.golangci.yml` 409 - `.golangci.toml` 410 - `.golangci.json` 411 412 GolangCI-Lint also searches for config files in all directories from the directory of the first analyzed path up to the root. 413 To see which config file is being used and where it was sourced from run golangci-lint with `-v` option. 414 415 Config options inside the file are identical to command-line options. 416 You can configure specific linters' options only within the config file (not the command-line). 417 418 There is a [`.golangci.example.yml`](https://github.com/golangci/golangci-lint/blob/master/.golangci.example.yml) example 419 config file with all supported options, their description and default value: 420 ```yaml 421 # This file contains all available configuration options 422 # with their default values. 423 424 # options for analysis running 425 run: 426 # default concurrency is a available CPU number 427 concurrency: 4 428 429 # timeout for analysis, e.g. 30s, 5m, default is 1m 430 deadline: 1m 431 432 # exit code when at least one issue was found, default is 1 433 issues-exit-code: 1 434 435 # include test files or not, default is true 436 tests: true 437 438 # list of build tags, all linters use it. Default is empty list. 439 build-tags: 440 - mytag 441 442 # which dirs to skip: they won't be analyzed; 443 # can use regexp here: generated.*, regexp is applied on full path; 444 # default value is empty list, but next dirs are always skipped independently 445 # from this option's value: 446 # vendor$, third_party$, testdata$, examples$, Godeps$, builtin$ 447 skip-dirs: 448 - src/external_libs 449 - autogenerated_by_my_lib 450 451 # which files to skip: they will be analyzed, but issues from them 452 # won't be reported. Default value is empty list, but there is 453 # no need to include all autogenerated files, we confidently recognize 454 # autogenerated files. If it's not please let us know. 455 skip-files: 456 - ".*\\.my\\.go$" 457 - lib/bad.go 458 459 460 # output configuration options 461 output: 462 # colored-line-number|line-number|json|tab|checkstyle, default is "colored-line-number" 463 format: colored-line-number 464 465 # print lines of code with issue, default is true 466 print-issued-lines: true 467 468 # print linter name in the end of issue text, default is true 469 print-linter-name: true 470 471 472 # all available settings of specific linters 473 linters-settings: 474 errcheck: 475 # report about not checking of errors in type assetions: `a := b.(MyStruct)`; 476 # default is false: such cases aren't reported by default. 477 check-type-assertions: false 478 479 # report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`; 480 # default is false: such cases aren't reported by default. 481 check-blank: false 482 govet: 483 # report about shadowed variables 484 check-shadowing: true 485 486 # Obtain type information from installed (to $GOPATH/pkg) package files: 487 # golangci-lint will execute `go install -i` and `go test -i` for analyzed packages 488 # before analyzing them. 489 # By default this option is disabled and govet gets type information by loader from source code. 490 # Loading from source code is slow, but it's done only once for all linters. 491 # Go-installing of packages first time is much slower than loading them from source code, 492 # therefore this option is disabled by default. 493 # But repeated installation is fast in go >= 1.10 because of build caching. 494 # Enable this option only if all conditions are met: 495 # 1. you use only "fast" linters (--fast e.g.): no program loading occurs 496 # 2. you use go >= 1.10 497 # 3. you do repeated runs (false for CI) or cache $GOPATH/pkg or `go env GOCACHE` dir in CI. 498 use-installed-packages: false 499 golint: 500 # minimal confidence for issues, default is 0.8 501 min-confidence: 0.8 502 gofmt: 503 # simplify code: gofmt with `-s` option, true by default 504 simplify: true 505 gocyclo: 506 # minimal code complexity to report, 30 by default (but we recommend 10-20) 507 min-complexity: 10 508 maligned: 509 # print struct with more effective memory layout or not, false by default 510 suggest-new: true 511 dupl: 512 # tokens count to trigger issue, 150 by default 513 threshold: 100 514 goconst: 515 # minimal length of string constant, 3 by default 516 min-len: 3 517 # minimal occurrences count to trigger, 3 by default 518 min-occurrences: 3 519 depguard: 520 list-type: blacklist 521 include-go-root: false 522 packages: 523 - github.com/davecgh/go-spew/spew 524 misspell: 525 # Correct spellings using locale preferences for US or UK. 526 # Default is to use a neutral variety of English. 527 # Setting locale to US will correct the British spelling of 'colour' to 'color'. 528 locale: US 529 lll: 530 # max line length, lines longer will be reported. Default is 120. 531 # '\t' is counted as 1 character by default, and can be changed with the tab-width option 532 line-length: 120 533 # tab width in spaces. Default to 1. 534 tab-width: 1 535 unused: 536 # treat code as a program (not a library) and report unused exported identifiers; default is false. 537 # XXX: if you enable this setting, unused will report a lot of false-positives in text editors: 538 # if it's called for subdir of a project it can't find funcs usages. All text editor integrations 539 # with golangci-lint call it on a directory with the changed file. 540 check-exported: false 541 unparam: 542 # call graph construction algorithm (cha, rta). In general, use cha for libraries, 543 # and rta for programs with main packages. Default is cha. 544 algo: cha 545 546 # Inspect exported functions, default is false. Set to true if no external program/library imports your code. 547 # XXX: if you enable this setting, unparam will report a lot of false-positives in text editors: 548 # if it's called for subdir of a project it can't find external interfaces. All text editor integrations 549 # with golangci-lint call it on a directory with the changed file. 550 check-exported: false 551 nakedret: 552 # make an issue if func has more lines of code than this setting and it has naked returns; default is 30 553 max-func-lines: 30 554 prealloc: 555 # XXX: we don't recommend using this linter before doing performance profiling. 556 # For most programs usage of prealloc will be a premature optimization. 557 558 # Report preallocation suggestions only on simple loops that have no returns/breaks/continues/gotos in them. 559 # True by default. 560 simple: true 561 range-loops: true # Report preallocation suggestions on range loops, true by default 562 for-loops: false # Report preallocation suggestions on for loops, false by default 563 564 565 linters: 566 enable: 567 - megacheck 568 - govet 569 enable-all: false 570 disable: 571 - maligned 572 - prealloc 573 disable-all: false 574 presets: 575 - bugs 576 - unused 577 fast: false 578 579 580 issues: 581 # List of regexps of issue texts to exclude, empty list by default. 582 # But independently from this option we use default exclude patterns, 583 # it can be disabled by `exclude-use-default: false`. To list all 584 # excluded by default patterns execute `golangci-lint run --help` 585 exclude: 586 - abcdef 587 588 # Independently from option `exclude` we use default exclude patterns, 589 # it can be disabled by this option. To list all 590 # excluded by default patterns execute `golangci-lint run --help`. 591 # Default value for this option is true. 592 exclude-use-default: false 593 594 # Maximum issues count per one linter. Set to 0 to disable. Default is 50. 595 max-per-linter: 0 596 597 # Maximum count of issues with the same text. Set to 0 to disable. Default is 3. 598 max-same: 0 599 600 # Show only new issues: if there are unstaged changes or untracked files, 601 # only those changes are analyzed, else only changes in HEAD~ are analyzed. 602 # It's a super-useful option for integration of golangci-lint into existing 603 # large codebase. It's not practical to fix all existing issues at the moment 604 # of integration: much better don't allow issues in new code. 605 # Default is false. 606 new: false 607 608 # Show only new issues created after git revision `REV` 609 new-from-rev: REV 610 611 # Show only new issues created in git patch with set file path. 612 new-from-patch: path/to/patch/file 613 ``` 614 615 It's a [.golangci.yml](https://github.com/golangci/golangci-lint/blob/master/.golangci.yml) config file of this repo: we enable more linters 616 than the default and have more strict settings: 617 ```yaml 618 linters-settings: 619 govet: 620 check-shadowing: true 621 golint: 622 min-confidence: 0 623 gocyclo: 624 min-complexity: 10 625 maligned: 626 suggest-new: true 627 dupl: 628 threshold: 100 629 goconst: 630 min-len: 2 631 min-occurrences: 2 632 depguard: 633 list-type: blacklist 634 packages: 635 # logging is allowed only by logutils.Log, logrus 636 # is allowed to use only in logutils package 637 - github.com/sirupsen/logrus 638 misspell: 639 locale: US 640 641 linters: 642 enable-all: true 643 disable: 644 - maligned 645 - prealloc 646 ``` 647 648 # False Positives 649 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: 650 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. 651 2. Exclude this one issue by using special comment `// nolint[:linter1,linter2,...]` on issued line. 652 Comment `// nolint` disables all issues reporting on this line. Comment e.g. `// nolint:govet` disables only govet issues for this line. 653 If you would like to completely exclude all issues for some function prepend this comment 654 above function: 655 ```go 656 //nolint 657 func f() { 658 ... 659 } 660 ``` 661 662 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. 663 664 # FAQ 665 **How do you add a custom linter?** 666 667 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. 668 669 **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** 670 671 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. 672 By doing this you won't create new issues in your code and can choose fix existing issues (or not). 673 674 **How to use `golangci-lint` in CI (Continuous Integration)?** 675 676 You have 2 choices: 677 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). 678 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. 679 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. 680 681 **Does I need to run `go install`?** 682 683 No, you don't need to do it anymore. We will run `go install -i` and `go test -i` 684 for analyzed packages ourselves. We will run them only 685 if option `govet.use-installed-packages` is `true`. 686 687 **`golangci-lint` doesn't work** 688 689 1. Update it: `go get -u github.com/golangci/golangci-lint/cmd/golangci-lint` 690 2. Run it with `-v` option and check the output. 691 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. 692 693 # Thanks 694 Thanks to [alecthomas/gometalinter](https://github.com/alecthomas/gometalinter) for inspiration and amazing work. 695 Thanks to [bradleyfalzon/revgrep](https://github.com/bradleyfalzon/revgrep) for cool diff tool. 696 697 Thanks to developers and authors of used linters: 698 - [kisielk](https://github.com/kisielk) 699 - [golang](https://github.com/golang) 700 - [dominikh](https://github.com/dominikh) 701 - [GoASTScanner](https://github.com/GoASTScanner) 702 - [opennota](https://github.com/opennota) 703 - [mvdan](https://github.com/mvdan) 704 - [mdempsky](https://github.com/mdempsky) 705 - [gordonklaus](https://github.com/gordonklaus) 706 - [mibk](https://github.com/mibk) 707 - [jgautheron](https://github.com/jgautheron) 708 - [remyoudompheng](https://github.com/remyoudompheng) 709 - [alecthomas](https://github.com/alecthomas) 710 - [OpenPeeDeeP](https://github.com/OpenPeeDeeP) 711 - [client9](https://github.com/client9) 712 - [walle](https://github.com/walle) 713 - [alexkohler](https://github.com/alexkohler) 714 715 # Future Plans 716 1. Upstream all changes of forked linters. 717 2. Fully integrate all used linters: make a common interface and reuse 100% of what can be reused: AST traversal, packages preparation etc. 718 3. Make it easy to write own linter/checker: it should take a minimum code, have perfect documentation, debugging and testing tooling. 719 4. Speed up package loading (dig into [loader](golang.org/x/tools/go/loader)): on-disk cache and existing code profiling-optimizing. 720 5. Analyze (don't only filter) only new code: analyze only changed files and dependencies, make incremental analysis, caches. 721 6. Smart new issues detector: don't print existing issues on changed lines. 722 7. Integration with Text Editors. On-the-fly code analysis for text editors: it should be super-fast. 723 8. Minimize false-positives by fixing linters and improving testing tooling. 724 9. Automatic issues fixing (code rewrite, refactoring) where it's possible. 725 10. Documentation for every issue type. 726 727 # Changelog 728 729 There is the most valuable changes log: 730 731 ## June 2018 732 733 1. Add support of the next linters: 734 * unparam 735 * misspell 736 * prealloc 737 * nakedret 738 * lll 739 * depguard 740 2. Smart generated files detector 741 3. Full `//nolint` support 742 4. Implement `--skip-files` and `--skip-dirs` options 743 5. Checkstyle output format support 744 745 ## May 2018 746 747 1. Support GitHub Releases 748 2. Installation via Homebrew and Docker 749 750 # Contact Information 751 You can contact the [author](https://github.com/jirfag) of GolangCI-Lint 752 by [denis@golangci.com](mailto:denis@golangci.com).