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

[dot-imports] support allow list of packages #939

Merged
merged 1 commit into from
Nov 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion RULES_DESCRIPTIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,17 @@ _Description_: Importing with `.` makes the programs much harder to understand b

More information [here](https://github.com/golang/go/wiki/CodeReviewComments#import-dot)

_Configuration_: N/A
_Configuration_:

* `allowedPackages`: (list of strings) comma-separated list of allowed dot import packages

Example:

```toml
[rule.dot-imports]
arguments = [{ allowedPackages = ["github.com/onsi/ginkgo/v2","github.com/onsi/gomega"] }]
```


## duplicated-imports

Expand Down
65 changes: 59 additions & 6 deletions rule/dot-imports.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@
package rule

import (
"fmt"
"go/ast"
"sync"

"github.com/mgechev/revive/lint"
)

// DotImportsRule lints given else constructs.
type DotImportsRule struct{}
type DotImportsRule struct {
sync.Mutex
allowedPackages allowPackages
}

// Apply applies the rule to given file.
func (*DotImportsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
func (r *DotImportsRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure {
r.configure(arguments)

var failures []lint.Failure

fileAst := file.AST
Expand All @@ -20,6 +27,7 @@ func (*DotImportsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
onFailure: func(failure lint.Failure) {
failures = append(failures, failure)
},
allowPackages: r.allowedPackages,
}

ast.Walk(walker, fileAst)
Expand All @@ -32,15 +40,49 @@ func (*DotImportsRule) Name() string {
return "dot-imports"
}

func (r *DotImportsRule) configure(arguments lint.Arguments) {
r.Lock()
defer r.Unlock()

if r.allowedPackages != nil {
return
}

r.allowedPackages = make(allowPackages)
if len(arguments) == 0 {
return
}

args, ok := arguments[0].(map[string]any)
if !ok {
panic(fmt.Sprintf("Invalid argument to the dot-imports rule. Expecting a k,v map, got %T", arguments[0]))
}

if allowedPkgArg, ok := args["allowedPackages"]; ok {
if pkgs, ok := allowedPkgArg.([]any); ok {
for _, p := range pkgs {
if pkg, ok := p.(string); ok {
r.allowedPackages.add(pkg)
} else {
panic(fmt.Sprintf("Invalid argument to the dot-imports rule, string expected. Got '%v' (%T)", p, p))
}
}
} else {
panic(fmt.Sprintf("Invalid argument to the dot-imports rule, []string expected. Got '%v' (%T)", allowedPkgArg, allowedPkgArg))
}
}
}

type lintImports struct {
file *lint.File
fileAst *ast.File
onFailure func(lint.Failure)
file *lint.File
fileAst *ast.File
onFailure func(lint.Failure)
allowPackages allowPackages
}

func (w lintImports) Visit(_ ast.Node) ast.Visitor {
for _, is := range w.fileAst.Imports {
if is.Name != nil && is.Name.Name == "." {
if is.Name != nil && is.Name.Name == "." && !w.allowPackages.isAllowedPackage(is.Path.Value) {
w.onFailure(lint.Failure{
Confidence: 1,
Failure: "should not use dot imports",
Expand All @@ -51,3 +93,14 @@ func (w lintImports) Visit(_ ast.Node) ast.Visitor {
}
return nil
}

type allowPackages map[string]struct{}

func (ap allowPackages) add(pkg string) {
ap[fmt.Sprintf(`"%s"`, pkg)] = struct{}{} // import path strings are with double quotes
}

func (ap allowPackages) isAllowedPackage(pkg string) bool {
_, allowed := ap[pkg]
return allowed
}
18 changes: 18 additions & 0 deletions test/dot_imports_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package test

import (
"testing"

"github.com/mgechev/revive/lint"
"github.com/mgechev/revive/rule"
)

func TestDotImports(t *testing.T) {
nunnatsa marked this conversation as resolved.
Show resolved Hide resolved
args := []any{map[string]any{
"allowedPackages": []any{"errors", "context", "github.com/BurntSushi/toml"},
}}

testRule(t, "import-dot", &rule.DotImportsRule{}, &lint.RuleConfig{
Arguments: args,
})
}
22 changes: 22 additions & 0 deletions testdata/import-dot.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Test that dot imports are flagged.

package fixtures

import (
. "context" // in allowedPackages (standard library => just the name without full path)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we please have a non-aliased and aliased imports to make sure they are not affected.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the review @denisvmedia. Fixed. PTAL.

. "errors" // in allowedPackages (standard library => just the name without full path)
. "fmt" // MATCH /should not use dot imports/
"math/rand"
tmplt "text/template"

. "github.com/BurntSushi/toml" // in allowedPackages (not in the standard library)
)

var _ Stringer // from "fmt"
var _ = New("fake error")
var _ = Background()

var _ = Position{} // check a package not in the standard library

var _ = rand.Rand{} // check non-alias package
var _ = tmplt.Template{} // check alias package
Loading