Skip to content

Commit

Permalink
refactor: collect reports before flush
Browse files Browse the repository at this point in the history
  • Loading branch information
kulti committed Jan 8, 2021
1 parent d82170c commit f3e8da7
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 6 deletions.
16 changes: 10 additions & 6 deletions pkg/analyzer/analyzer.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ func (t thelper) run(pass *analysis.Pass) (interface{}, error) {
return nil, nil
}

var reports reports
inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
nodeFilter := []ast.Node{
(*ast.FuncDecl)(nil),
Expand All @@ -145,9 +146,12 @@ func (t thelper) run(pass *analysis.Pass) (interface{}, error) {
return
}

checkFunc(pass, fd, tCheckOpts)
checkFunc(pass, fd, bCheckOpts)
checkFunc(pass, &reports, fd, tCheckOpts)
checkFunc(pass, &reports, fd, bCheckOpts)
})

reports.Flush(pass)

return nil, nil
}

Expand Down Expand Up @@ -215,7 +219,7 @@ type funcDecl struct {
Body *ast.BlockStmt
}

func checkFunc(pass *analysis.Pass, funcDecl funcDecl, opts checkFuncOpts) {
func checkFunc(pass *analysis.Pass, reports *reports, funcDecl funcDecl, opts checkFuncOpts) {
if strings.HasPrefix(funcDecl.Name.Name, opts.skipPrefix) {
return
}
Expand All @@ -234,20 +238,20 @@ func checkFunc(pass *analysis.Pass, funcDecl funcDecl, opts checkFuncOpts) {
}

if !checkFirstPassed {
pass.Reportf(funcDecl.Pos, "parameter %s should be the first or after context.Context", opts.tbType)
reports.Reportf(funcDecl.Pos, "parameter %s should be the first or after context.Context", opts.tbType)
}
}
}

if opts.checkName {
if len(p.Names) > 0 && p.Names[0].Name != opts.varName {
pass.Reportf(funcDecl.Pos, "parameter %s should have name %s", opts.tbType, opts.varName)
reports.Reportf(funcDecl.Pos, "parameter %s should have name %s", opts.tbType, opts.varName)
}
}

if opts.checkBegin {
if len(funcDecl.Body.List) == 0 || !isTHelperCall(pass, funcDecl.Body.List[0], opts.tbHelper) {
pass.Reportf(funcDecl.Pos, "test helper function should start from %s.Helper()", opts.varName)
reports.Reportf(funcDecl.Pos, "test helper function should start from %s.Helper()", opts.varName)
}
}
}
Expand Down
31 changes: 31 additions & 0 deletions pkg/analyzer/report.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package analyzer

import (
"go/token"

"golang.org/x/tools/go/analysis"
)

type reports struct {
reports []report
}

type report struct {
pos token.Pos
format string
args []interface{}
}

func (rr *reports) Reportf(pos token.Pos, format string, args ...interface{}) {
rr.reports = append(rr.reports, report{
pos: pos,
format: format,
args: args,
})
}

func (rr reports) Flush(pass *analysis.Pass) {
for _, r := range rr.reports {
pass.Reportf(r.pos, r.format, r.args...)
}
}

0 comments on commit f3e8da7

Please sign in to comment.