-
Notifications
You must be signed in to change notification settings - Fork 41
Description
Hi, I hope this feature request isn't duplicating anything else — I wasn't able to find something similar after looking through the existing repo issues.
In my organization we'd like to write a rule that flags uses of context.Background()
outside of package main
, e.g.:
// This is okay
package main
import "context"
func main() {
_ = context.Background()
}
// this should trigger the rule
package foo
import "context"
func DoSomething() {
_ = context.Background()
}
Unfortunately, dsl.File
doesn't seem to provide a way to do this, as it only provides the Name
(filename) and PkgPath
(import path, which does not include the package name itself). Since multiple files can be in package main
, we don't have a good way to filter out files other than main.go
.
Side note — while debugging it was kind of hard to figure out what the package path actually contained. It might be useful to show what was rejected with
-debug-group
instead of just printingrejected by m.File().PkgPath.Matches("...")
).
I also tried some workarounds, like looking for m.Match("package $main")
and other similar combinations, but it seems like the package declaration is special and not included in the AST normally, so I was never able to construct a pattern that matched the package main
declaration.
From looking at the PkgPath
filtering, it seems like a similar implementation could work using pkg.Name()
instead of pkg.Path()
here: https://github.com/quasilyte/go-ruleguard/blob/master/ruleguard/filters.go#L88-L96
I propose adding a (dsl.File).PkgName
field, corresponding to (*types.Package).Name()
, which can be used to filter the same way as PkgPath
if you think this is a reasonable use case, and there is no other workaround. Thanks!