| 1 |
package gitattributes |
| 2 |
|
| 3 |
// Matcher defines a global multi-pattern matcher for gitattributes patterns |
| 4 |
type Matcher interface { |
| 5 |
// Match matches patterns in the order of priorities. |
| 6 |
Match(path []string, attributes []string) (map[string]Attribute, bool) |
| 7 |
} |
| 8 |
|
| 9 |
type MatcherOptions struct{} |
| 10 |
|
| 11 |
// NewMatcher constructs a new matcher. Patterns must be given in the order of |
| 12 |
// increasing priority. That is the most generic settings files first, then the |
| 13 |
// content of the repo .gitattributes, then content of .gitattributes down the |
| 14 |
// path. |
| 15 |
func NewMatcher(stack []MatchAttribute) Matcher { |
| 16 |
m := &matcher{stack: stack} |
| 17 |
m.init() |
| 18 |
|
| 19 |
return m |
| 20 |
} |
| 21 |
|
| 22 |
type matcher struct { |
| 23 |
stack []MatchAttribute |
| 24 |
macros map[string]MatchAttribute |
| 25 |
} |
| 26 |
|
| 27 |
func (m *matcher) init() { |
| 28 |
m.macros = make(map[string]MatchAttribute) |
| 29 |
|
| 30 |
for _, attr := range m.stack { |
| 31 |
if attr.Pattern == nil { |
| 32 |
m.macros[attr.Name] = attr |
| 33 |
} |
| 34 |
} |
| 35 |
} |
| 36 |
|
| 37 |
// Match matches path against the patterns in gitattributes files and returns |
| 38 |
// the attributes associated with the path. |
| 39 |
// |
| 40 |
// Specific attributes can be specified otherwise all attributes are returned. |
| 41 |
// |
| 42 |
// Matched is true if any path was matched to a rule, even if the results map |
| 43 |
// is empty. |
| 44 |
func (m *matcher) Match(path []string, attributes []string) (results map[string]Attribute, matched bool) { |
| 45 |
results = make(map[string]Attribute, len(attributes)) |
| 46 |
|
| 47 |
n := len(m.stack) |
| 48 |
for i := n - 1; i >= 0; i-- { |
| 49 |
if len(attributes) > 0 && len(attributes) == len(results) { |
| 50 |
return |
| 51 |
} |
| 52 |
|
| 53 |
pattern := m.stack[i].Pattern |
| 54 |
if pattern == nil { |
| 55 |
continue |
| 56 |
} |
| 57 |
|
| 58 |
if match := pattern.Match(path); match { |
| 59 |
matched = true |
| 60 |
for _, attr := range m.stack[i].Attributes { |
| 61 |
if attr.IsSet() { |
| 62 |
m.expandMacro(attr.Name(), results) |
| 63 |
} |
| 64 |
results[attr.Name()] = attr |
| 65 |
} |
| 66 |
} |
| 67 |
} |
| 68 |
return |
| 69 |
} |
| 70 |
|
| 71 |
func (m *matcher) expandMacro(name string, results map[string]Attribute) bool { |
| 72 |
if macro, ok := m.macros[name]; ok { |
| 73 |
for _, attr := range macro.Attributes { |
| 74 |
results[attr.Name()] = attr |
| 75 |
} |
| 76 |
} |
| 77 |
return false |
| 78 |
} |