Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow filtering by package name (not just path) #458

Open
ian-h-chamberlain opened this issue Aug 23, 2023 · 0 comments
Open

Allow filtering by package name (not just path) #458

ian-h-chamberlain opened this issue Aug 23, 2023 · 0 comments

Comments

@ian-h-chamberlain
Copy link

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 printing rejected 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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant