Created a custom plugin for golangci-lint
linter which just verifies imports in the go.mod
file against the whitelisted ones. Now, if linter finds a disallowed dependency it reports:
goModPath := filepath.Join(modRoot, "go.mod")
data, err := os.ReadFile(goModPath)
if err != nil {
// ...
}
modFile, err := modfile.Parse("go.mod", data, nil)
if err != nil {
// ...
}
for _, req := range modFile.Require {
isAllowed := false
for _, allowed := range config.AllowedDependencies {
if strings.HasPrefix(req.Mod.Path, allowed) {
isAllowed = true
break
}
}
if !isAllowed {
pass.Reportf(pass.Files[0].Package, "dependency '%s' is not in the list of allowed dependencies", req.Mod.Path)
}
}
}
The problem is that this report will point to the base package and looks like something like this:
logging/gcp.go:1:1: dependency 'cloud.google.com/go/logging' is not in the list of allowed dependencies
How can I get token position from the modFile.Require
(req
) that it will point to the corresponding line of the go.mod
file where found disallowed report?
Tried this way also:
startPos := req.Syntax.Start.Byte
pos := token.Pos(startPos)
pass.Reportf(pos, "dependency '%s' is not in the list of allowed dependencies", req.Mod.Path)
However, it doesn't help much. Getting this report:
$GOROOT/src/internal/race/norace.go:43:27: dependency 'cloud.google.com/go/logging' is not in the list of allowed dependencies
Any idea how this can be fixed? Thanks.