Skip to content

Commit

Permalink
add nolint skip support
Browse files Browse the repository at this point in the history
  • Loading branch information
kkHAIKE committed Sep 3, 2022
1 parent a2c3e11 commit 7be313c
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,23 @@ func NoInheritCancel(_ context.Context) (context.Context,context.CancelFunc) {
}
```

You can add `// nolint: contextcheck` in function decl doc comment, to skip this linter in some false-positive case.

```go
// nolint: contextcheck
func call1() {
doSomeThing(context.Background()) // add nolint will no issuss for that
}

func call2(ctx context.Context) {
call1()
}

func call3() {
call2(context.Background())
}
```

## Installation

You can get `contextcheck` by `go get` command.
Expand Down
33 changes: 33 additions & 0 deletions contextcheck.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package contextcheck
import (
"go/ast"
"go/types"
"regexp"
"strconv"
"strings"
"sync"
Expand Down Expand Up @@ -239,9 +240,41 @@ func (r *runner) checkIsEntry(f *ssa.Function) entryType {
return EntryWithHttpHandler
}

if r.skipByNolint(f) {
return EntryNone
}

return EntryNormal
}

var nolintRe = regexp.MustCompile(`^//\s?nolint:`)

func (r *runner) skipByNolint(f *ssa.Function) bool {
file := analysisutil.File(r.pass, f.Pos())
if file == nil {
return false
}

// only support FuncDecl comment
var fd *ast.FuncDecl
for _, v := range file.Decls {
if tmp, ok := v.(*ast.FuncDecl); ok && tmp.Name.Pos() == f.Pos() {
fd = tmp
break
}
}
if fd == nil || fd.Doc == nil || len(fd.Doc.List) == 0 {
return false
}

for _, v := range fd.Doc.List {
if len(nolintRe.FindString(v.Text)) > 0 && strings.Contains(v.Text, "contextcheck") {
return true
}
}
return false
}

func (r *runner) checkIsCtx(f *ssa.Function) (in, out bool) {
// check params
tuple := f.Signature.Params()
Expand Down
7 changes: 7 additions & 0 deletions testdata/src/a/a.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,11 @@ func f10(in bool, w http.ResponseWriter, r *http.Request) {
f8(context.Background(), w, r)
}

// nolint: contextcheck
func f14(w http.ResponseWriter, r *http.Request, err error) {
f8(r.Context(), w, r)
}

func f11() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
f8(r.Context(), w, r)
Expand All @@ -118,6 +123,8 @@ func f11() {

// f10 should be like `func f10(ctx context.Context, in bool, w http.ResponseWriter, r *http.Request)`
f10(true, w, r) // want "Function `f10` should pass the context parameter"

f14(w, r, nil)
})
}

Expand Down

0 comments on commit 7be313c

Please sign in to comment.