-
Notifications
You must be signed in to change notification settings - Fork 13
/
config.go
80 lines (68 loc) · 1.35 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package importas
import (
"errors"
"fmt"
"regexp"
"sync"
)
type Config struct {
RequiredAlias aliasList
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
}
rules := make([]*Rule, 0, len(c.RequiredAlias))
for _, aliases := range c.RequiredAlias {
path, alias := aliases[0], aliases[1]
reg, err := regexp.Compile(fmt.Sprintf("^%s$", path))
if err != nil {
return 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
}
func (c *Config) AliasFor(path string) (string, bool) {
rule := c.findRule(path)
if rule == nil {
return "", false
}
alias, err := rule.aliasFor(path)
if err != nil {
return "", false
}
return alias, true
}
type Rule struct {
Alias string
Regexp *regexp.Regexp
}
func (r *Rule) aliasFor(path string) (string, error) {
str := r.Regexp.FindString(path)
if len(str) > 0 {
return r.Regexp.ReplaceAllString(str, r.Alias), nil
}
return "", errors.New("mismatch rule")
}