diff --git a/.golangci.example.yml b/.golangci.example.yml index 7069ca904b2c..968a131a3dba 100644 --- a/.golangci.example.yml +++ b/.golangci.example.yml @@ -78,6 +78,11 @@ linters-settings: # path to a file containing a list of functions to exclude from checking # see https://github.com/kisielk/errcheck#excluding-functions for details exclude: /path/to/file.txt + + funlen: + lines: 60 + statements: 40 + govet: # report about shadowed variables check-shadowing: true diff --git a/.golangci.yml b/.golangci.yml index 85b508e6c6c0..c412cefa8a7a 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -46,6 +46,7 @@ linters: - maligned - prealloc - gochecknoglobals + - funlen run: skip-dirs: diff --git a/README.md b/README.md index dd3c3681e5c9..16b81b64a69f 100644 --- a/README.md +++ b/README.md @@ -208,6 +208,7 @@ Disabled by default linters: bodyclose: checks whether HTTP response body is closed successfully [fast: false, auto-fix: false] depguard: Go linter that checks if package imports are in a list of acceptable packages [fast: true, auto-fix: false] dupl: Tool for code clone detection [fast: true, auto-fix: false] +funlen: Tool for detection of long functions [fast: true, auto-fix: false] gochecknoglobals: Checks that no globals are present in Go code [fast: true, auto-fix: false] gochecknoinits: Checks that no init functions are present in Go code [fast: true, auto-fix: false] goconst: Finds repeated strings that could be replaced by a constant [fast: true, auto-fix: false] @@ -440,6 +441,7 @@ golangci-lint help linters - [gocritic](https://github.com/go-critic/go-critic) - The most opinionated Go source code linter - [gochecknoinits](https://github.com/leighmcculloch/gochecknoinits) - Checks that no init functions are present in Go code - [gochecknoglobals](https://github.com/leighmcculloch/gochecknoglobals) - Checks that no globals are present in Go code +- [funlen](https://github.com/ultraware/funlen) - Tool for detection of long functions ## Configuration @@ -629,6 +631,11 @@ linters-settings: # path to a file containing a list of functions to exclude from checking # see https://github.com/kisielk/errcheck#excluding-functions for details exclude: /path/to/file.txt + + funlen: + lines: 60 + statements: 40 + govet: # report about shadowed variables check-shadowing: true @@ -859,6 +866,7 @@ linters: - maligned - prealloc - gochecknoglobals + - funlen run: skip-dirs: @@ -999,6 +1007,7 @@ Thanks to developers and authors of used linters: - [kyoh86](https://github.com/kyoh86) - [go-critic](https://github.com/go-critic) - [leighmcculloch](https://github.com/leighmcculloch) +- [ultraware](https://github.com/ultraware) ## Changelog diff --git a/go.mod b/go.mod index 76c7e446397e..73c565affe56 100644 --- a/go.mod +++ b/go.mod @@ -49,6 +49,7 @@ require ( github.com/spf13/pflag v1.0.1 github.com/spf13/viper v1.0.2 github.com/stretchr/testify v1.2.2 + github.com/ultraware/funlen v0.0.1 github.com/timakin/bodyclose v0.0.0-00010101000000-87058b9bfcec github.com/valyala/quicktemplate v1.1.1 golang.org/x/crypto v0.0.0-20190313024323-a1f597ede03a // indirect diff --git a/go.sum b/go.sum index 631595838a6e..54d03232ab05 100644 --- a/go.sum +++ b/go.sum @@ -164,6 +164,8 @@ github.com/spf13/viper v1.0.2 h1:Ncr3ZIuJn322w2k1qmzXDnkLAdQMlJqBa9kfAH+irso= github.com/spf13/viper v1.0.2/go.mod h1:A8kyI5cUJhb8N+3pkfONlcEcZbueH6nhAm0Fq7SrnBM= github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/ultraware/funlen v0.0.1 h1:UeC9tpM4wNWzUJfan8z9sFE4QCzjjzlCZmuJN+aOkH0= +github.com/ultraware/funlen v0.0.1/go.mod h1:Dp4UiAus7Wdb9KUZsYWZEWiRzGuM2kXM1lPbfaF6xhA= github.com/timakin/bodyclose v0.0.0-00010101000000-87058b9bfcec h1:Ha5Eixh5Dgi14hDFFWsxoB/jR95rHjB1biKdK9VKkbQ= github.com/timakin/bodyclose v0.0.0-00010101000000-87058b9bfcec/go.mod h1:Qimiffbc6q9tBWlVV6x0P9sat/ao1xEkREYPPj9hphk= github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= diff --git a/pkg/config/config.go b/pkg/config/config.go index 9a113fe6d892..47297e043f77 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -164,6 +164,10 @@ type LintersSettings struct { Unused struct { CheckExported bool `mapstructure:"check-exported"` } + Funlen struct { + Lines int + Statements int + } Lll LllSettings Unparam UnparamSettings diff --git a/pkg/golinters/funlen.go b/pkg/golinters/funlen.go new file mode 100644 index 000000000000..1a24e24584d6 --- /dev/null +++ b/pkg/golinters/funlen.go @@ -0,0 +1,46 @@ +package golinters + +import ( + "context" + "go/token" + + "github.com/golangci/golangci-lint/pkg/lint/linter" + "github.com/golangci/golangci-lint/pkg/result" + + "github.com/ultraware/funlen" +) + +type Funlen struct{} + +func (Funlen) Name() string { + return "funlen" +} + +func (Funlen) Desc() string { + return "Tool for detection of long functions" +} + +func (f Funlen) Run(ctx context.Context, lintCtx *linter.Context) ([]result.Issue, error) { + var issues []funlen.Message + for _, file := range lintCtx.ASTCache.GetAllValidFiles() { + issues = append(issues, funlen.Run(file.F, file.Fset, lintCtx.Settings().Funlen.Lines, lintCtx.Settings().Funlen.Statements)...) + } + + if len(issues) == 0 { + return nil, nil + } + + res := make([]result.Issue, len(issues)) + for k, i := range issues { + res[k] = result.Issue{ + Pos: token.Position{ + Filename: i.Pos.Filename, + Line: i.Pos.Line, + }, + Text: i.Message, + FromLinter: f.Name(), + } + } + + return res, nil +} diff --git a/pkg/lint/lintersdb/manager.go b/pkg/lint/lintersdb/manager.go index dd5c57ca6d94..c19b1dfb1852 100644 --- a/pkg/lint/lintersdb/manager.go +++ b/pkg/lint/lintersdb/manager.go @@ -237,6 +237,10 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { WithPresets(linter.PresetStyle). WithSpeed(10). WithURL("https://github.com/leighmcculloch/gochecknoglobals"), + linter.NewConfig(golinters.Funlen{}). + WithPresets(linter.PresetStyle). + WithSpeed(10). + WithURL("https://github.com/ultraware/funlen"), } isLocalRun := os.Getenv("GOLANGCI_COM_RUN") == "" diff --git a/test/testdata/funlen.go b/test/testdata/funlen.go new file mode 100644 index 000000000000..4f8fb8d7c507 --- /dev/null +++ b/test/testdata/funlen.go @@ -0,0 +1,43 @@ +//args: -Efunlen +//config: linters-settings.funlen.lines=20 +//config: linters-settings.funlen.statements=10 +package testdata + +func TooManyLines() { // ERROR "Function 'TooManyLines' is too long \(22 > 20\)" + t := struct { + A string + B string + C string + D string + E string + F string + G string + H string + I string + }{ + `a`, + `b`, + `c`, + `d`, + `e`, + `f`, + `g`, + `h`, + `i`, + } + _ = t +} + +func TooManyStatements() { // ERROR "Function 'TooManyStatements' has too many statements \(11 > 10\)" + a := 1 + b := a + c := b + d := c + e := d + f := e + g := f + h := g + i := h + j := i + _ = j +} diff --git a/vendor/github.com/ultraware/funlen/LICENSE b/vendor/github.com/ultraware/funlen/LICENSE new file mode 100644 index 000000000000..dca75556d8f0 --- /dev/null +++ b/vendor/github.com/ultraware/funlen/LICENSE @@ -0,0 +1,7 @@ +Copyright 2018 Ultraware Consultancy and Development B.V. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/ultraware/funlen/README.md b/vendor/github.com/ultraware/funlen/README.md new file mode 100644 index 000000000000..ca7e9a0f755e --- /dev/null +++ b/vendor/github.com/ultraware/funlen/README.md @@ -0,0 +1,69 @@ +# Funlen linter + +Funlen is a linter that checks for long functions. It can checks both on the number of lines and the number of statements. + +The default limits are 50 lines and 35 statements. You can configure these with the `-l` and `-s` flags. + +Example code: + +```go +package main + +import "fmt" + +func fiveStatements() { + fmt.Println(1) + fmt.Println(2) + fmt.Println(3) + fmt.Println(4) + fmt.Println(5) +} + +func sevenLines() { + fmt.Println(1) + + fmt.Println(2) + + fmt.Println(3) + + fmt.Println(4) +} +``` + +Reults in: + +``` +$ funlen -l=6 -s=4 . +main.go:5:6:Function 'fiveStatements' has too many statements (5 > 4) +main.go:13:6:Function 'sevenLines' is too long (7 > 6) +``` + +## Installation guide + +```bash +go get git.ultraware.nl/NiseVoid/funlen +``` + +### Gometalinter + +You can add funlen to gometalinter and enable it. + +`.gometalinter.json`: + +```json +{ + "Linters": { + "funlen": "funlen -l=50 -s=35:PATH:LINE:COL:MESSAGE" + }, + + "Enable": [ + "funlen" + ] +} +``` + +commandline: + +```bash +gometalinter --linter "funlen:funlen -l=50 -s=35:PATH:LINE:COL:MESSAGE" --enable "funlen" +``` diff --git a/vendor/github.com/ultraware/funlen/main.go b/vendor/github.com/ultraware/funlen/main.go new file mode 100644 index 000000000000..5a1ceeb791bd --- /dev/null +++ b/vendor/github.com/ultraware/funlen/main.go @@ -0,0 +1,98 @@ +package funlen + +import ( + "fmt" + "go/ast" + "go/token" + "reflect" +) + +const defaultLineLimit = 60 +const defaultStmtLimit = 40 + +// Run runs this linter on the provided code +func Run(file *ast.File, fset *token.FileSet, lineLimit, stmtLimit int) []Message { + if lineLimit == 0 { + lineLimit = defaultLineLimit + } + if stmtLimit == 0 { + stmtLimit = defaultStmtLimit + } + + var msgs []Message + for _, f := range file.Decls { + decl, ok := f.(*ast.FuncDecl) + if !ok { + continue + } + + if stmts := parseStmts(decl.Body.List); stmts > stmtLimit { + msgs = append(msgs, makeStmtMessage(fset, decl.Name, stmts, stmtLimit)) + continue + } + + if lines := getLines(fset, decl); lines > lineLimit { + msgs = append(msgs, makeLineMessage(fset, decl.Name, lines, lineLimit)) + } + } + + return msgs +} + +// Message contains a message +type Message struct { + Pos token.Position + Message string +} + +func makeLineMessage(fset *token.FileSet, funcInfo *ast.Ident, lines, lineLimit int) Message { + return Message{ + fset.Position(funcInfo.Pos()), + fmt.Sprintf("Function '%s' is too long (%d > %d)\n", funcInfo.Name, lines, lineLimit), + } +} + +func makeStmtMessage(fset *token.FileSet, funcInfo *ast.Ident, stmts, stmtLimit int) Message { + return Message{ + fset.Position(funcInfo.Pos()), + fmt.Sprintf("Function '%s' has too many statements (%d > %d)\n", funcInfo.Name, stmts, stmtLimit), + } +} + +func getLines(fset *token.FileSet, f *ast.FuncDecl) int { // nolint: interfacer + return fset.Position(f.End()).Line - fset.Position(f.Pos()).Line - 1 +} + +func parseStmts(s []ast.Stmt) (total int) { + for _, v := range s { + total++ + switch stmt := v.(type) { + case *ast.BlockStmt: + total += parseStmts(stmt.List) - 1 + case *ast.ForStmt, *ast.RangeStmt, *ast.IfStmt, + *ast.SwitchStmt, *ast.TypeSwitchStmt, *ast.SelectStmt: + total += parseBodyListStmts(stmt) + case *ast.CaseClause: + total += parseStmts(stmt.Body) + case *ast.AssignStmt: + total += checkInlineFunc(stmt.Rhs[0]) + case *ast.GoStmt: + total += checkInlineFunc(stmt.Call.Fun) + case *ast.DeferStmt: + total += checkInlineFunc(stmt.Call.Fun) + } + } + return +} + +func checkInlineFunc(stmt ast.Expr) int { + if block, ok := stmt.(*ast.FuncLit); ok { + return parseStmts(block.Body.List) + } + return 0 +} + +func parseBodyListStmts(t interface{}) int { + i := reflect.ValueOf(t).Elem().FieldByName(`Body`).Elem().FieldByName(`List`).Interface() + return parseStmts(i.([]ast.Stmt)) +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 66502bc0cf31..0f59176169f9 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -183,6 +183,8 @@ github.com/stretchr/testify/assert github.com/stretchr/testify/require # github.com/timakin/bodyclose v0.0.0-00010101000000-87058b9bfcec github.com/timakin/bodyclose/passes/bodyclose +# github.com/ultraware/funlen v0.0.1 +github.com/ultraware/funlen # github.com/valyala/bytebufferpool v1.0.0 github.com/valyala/bytebufferpool # github.com/valyala/quicktemplate v1.1.1