Add roughtime static code analysis and fix all violations (#5370)

* Add roughtime static code analysis and fix all violations
* Merge branch 'master' into enforce-roughtime
This commit is contained in:
Preston Van Loon
2020-04-09 16:35:42 -07:00
committed by GitHub
parent 7b8bad35e7
commit 7a5010ecea
15 changed files with 126 additions and 25 deletions

View File

@@ -0,0 +1,25 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_tool_library")
go_library(
name = "go_default_library",
srcs = ["analyzer.go"],
importpath = "github.com/prysmaticlabs/prysm/tools/analyzers/roughtime",
visibility = ["//visibility:public"],
deps = [
"@org_golang_x_tools//go/analysis:go_default_library",
"@org_golang_x_tools//go/analysis/passes/inspect:go_default_library",
"@org_golang_x_tools//go/ast/inspector:go_default_library",
],
)
go_tool_library(
name = "go_tool_library",
srcs = ["analyzer.go"],
importpath = "github.com/prysmaticlabs/prysm/tools/analyzers/roughtime",
visibility = ["//visibility:public"],
deps = [
"@org_golang_x_tools//go/analysis:go_tool_library",
"@org_golang_x_tools//go/analysis/passes/inspect:go_tool_library",
"@org_golang_x_tools//go/ast/inspector:go_tool_library",
],
)

View File

@@ -0,0 +1,52 @@
package roughtime
import (
"go/ast"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
)
// Doc explaining the tool.
const Doc = "Tool to enforce the use of roughtime.Now() rather than time.Now(). This is " +
"critically important to certain ETH2 systems where the client / server must be in sync with " +
"some NTP network."
// Analyzer runs static analysis.
var Analyzer = &analysis.Analyzer{
Name: "roughtime",
Doc: Doc,
Requires: []*analysis.Analyzer{inspect.Analyzer},
Run: run,
}
func run(pass *analysis.Pass) (interface{}, error) {
inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
nodeFilter := []ast.Node{
(*ast.CallExpr)(nil),
}
inspect.Preorder(nodeFilter, func(node ast.Node) {
if ce, ok := node.(*ast.CallExpr); ok {
if isPkgDot(ce.Fun, "time", "Now") {
pass.Reportf(node.Pos(), "Do not use time.Now(), use "+
"github.com/prysmaticlabs/prysm/shared/roughtime.Now() or add an exclusion "+
"to //:nogo.json.")
}
}
})
return nil, nil
}
func isPkgDot(expr ast.Expr, pkg, name string) bool {
sel, ok := expr.(*ast.SelectorExpr)
return ok && isIdent(sel.X, pkg) && isIdent(sel.Sel, name)
}
func isIdent(expr ast.Expr, ident string) bool {
id, ok := expr.(*ast.Ident)
return ok && id.Name == ident
}