generated from xmidt-org/.go-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
selector.go
66 lines (55 loc) · 1.61 KB
/
selector.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
package thoth
// SelectorConfig represents a set of templates whose relative paths match
// one or more patterns.
type SelectorConfig struct {
// Patterns are the globs which must match a template's name in order
// to use this configured parser.
Patterns []string `json:"patterns" yaml:"patterns"`
// Parser is the configuration for parsing templates that match any
// of the configured patterns.
Parser ParserConfig `json:"parser" yaml:"parser"`
}
// Selector is a strategy for determining how to parse a template based
// on that template's name. The name is typically a relative path, which
// may be matched via globbing.
type Selector interface {
// Select chooses a parser based on the template name. If no parser
// was found for the template, this method returns (nil, false).
Select(name string) (Parser, bool)
}
type matchEntry struct {
m Matcher
p Parser
}
type matchSelector struct {
entries []matchEntry
}
func (ms matchSelector) Select(name string) (p Parser, found bool) {
for _, e := range ms.entries {
found = e.m.Match(name)
if found {
p = e.p
break
}
}
return
}
// NewSelector constructs a Selector based on the given configurations.
// If an empty configs is passed, the returned Selector won't match
// any template names.
func NewSelector(configs ...SelectorConfig) (Selector, error) {
ms := &matchSelector{
entries: make([]matchEntry, len(configs)),
}
for i, c := range configs {
var err error
ms.entries[i].m, err = ParsePatterns(c.Patterns...)
if err == nil {
ms.entries[i].p, err = NewParser(c.Parser)
}
if err != nil {
return nil, err
}
}
return ms, nil
}