Skip to content
Open
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
7 changes: 4 additions & 3 deletions analyzer.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,19 +31,20 @@ func run(pass *analysis.Pass) (interface{}, error) {
}

func runWithConfig(config *Config, pass *analysis.Pass) (interface{}, error) {
if err := config.CompileRegexp(); err != nil {
c, err := config.Compile()
if err != nil {
return nil, err
}

inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
inspect.Preorder([]ast.Node{(*ast.ImportSpec)(nil)}, func(n ast.Node) {
visitImportSpecNode(config, n.(*ast.ImportSpec), pass)
visitImportSpecNode(c, n.(*ast.ImportSpec), pass)
})

return nil, nil
}

func visitImportSpecNode(config *Config, node *ast.ImportSpec, pass *analysis.Pass) {
func visitImportSpecNode(config *CompiledConfig, node *ast.ImportSpec, pass *analysis.Pass) {
if !config.DisallowUnaliased && node.Name == nil {
return
}
Expand Down
47 changes: 22 additions & 25 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,53 +4,40 @@ import (
"errors"
"fmt"
"regexp"
"sync"
)

type Config struct {
RequiredAlias map[string]string
Rules []*Rule
DisallowUnaliased bool
DisallowExtraAliases bool
muRules sync.Mutex
}

func (c *Config) CompileRegexp() error {
c.muRules.Lock()
defer c.muRules.Unlock()
if c.Rules != nil {
return nil
}
type CompiledConfig struct {
Config
rules []*Rule
}

func (c Config) Compile() (*CompiledConfig, error) {
rules := make([]*Rule, 0, len(c.RequiredAlias))
for path, alias := range c.RequiredAlias {
reg, err := regexp.Compile(fmt.Sprintf("^%s$", path))
if err != nil {
return err
return nil, err
}

rules = append(rules, &Rule{
Regexp: reg,
Alias: alias,
})
}
c.Rules = rules
return nil
}

func (c *Config) findRule(path string) *Rule {
c.muRules.Lock()
rules := c.Rules
c.muRules.Unlock()
for _, rule := range rules {
if rule.Regexp.MatchString(path) {
return rule
}
}

return nil
return &CompiledConfig{
Config: c,
rules: rules,
}, nil
}

func (c *Config) AliasFor(path string) (string, bool) {
func (c *CompiledConfig) AliasFor(path string) (string, bool) {
rule := c.findRule(path)
if rule == nil {
return "", false
Expand All @@ -64,6 +51,16 @@ func (c *Config) AliasFor(path string) (string, bool) {
return alias, true
}

func (c *CompiledConfig) findRule(path string) *Rule {
for _, rule := range c.rules {
if rule.Regexp.MatchString(path) {
return rule
}
}

return nil
}

type Rule struct {
Alias string
Regexp *regexp.Regexp
Expand Down