| 1 | package gitattr |
| 2 | |
| 3 | type MacroProcessor struct { |
| 4 | macros map[string][]*Attr |
| 5 | didReadMacros bool |
| 6 | } |
| 7 | |
| 8 | // NewMacroProcessor returns a new MacroProcessor object for parsing macros. |
| 9 | func NewMacroProcessor() *MacroProcessor { |
| 10 | macros := make(map[string][]*Attr) |
| 11 | |
| 12 | // This is built into Git. |
| 13 | macros["binary"] = []*Attr{ |
| 14 | {K: "diff", V: "false"}, |
| 15 | {K: "merge", V: "false"}, |
| 16 | {K: "text", V: "false"}, |
| 17 | } |
| 18 | |
| 19 | return &MacroProcessor{ |
| 20 | macros: macros, |
| 21 | didReadMacros: false, |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | // ProcessLines reads the specified lines, returning a new set of lines which |
| 26 | // all have a valid pattern. If readMacros is true, it additionally loads any |
| 27 | // macro lines as it reads them. |
| 28 | func (mp *MacroProcessor) ProcessLines(lines []Line, readMacros bool) []PatternLine { |
| 29 | result := make([]PatternLine, 0, len(lines)) |
| 30 | for _, line := range lines { |
| 31 | switch l := line.(type) { |
| 32 | case PatternLine: |
| 33 | var lineAttrs lineAttrs |
| 34 | lineAttrs.attrs = make([]*Attr, 0, len(l.Attrs())) |
| 35 | |
| 36 | resultLine := &patternLine{l.Pattern(), lineAttrs} |
| 37 | for _, attr := range l.Attrs() { |
| 38 | macros := mp.macros[attr.K] |
| 39 | if attr.V == "true" && macros != nil { |
| 40 | resultLine.attrs = append( |
| 41 | resultLine.attrs, |
| 42 | macros..., |
| 43 | ) |
| 44 | } else if attr.Unspecified && macros != nil { |
| 45 | for _, m := range macros { |
| 46 | resultLine.attrs = append( |
| 47 | resultLine.attrs, |
| 48 | &Attr{ |
| 49 | K: m.K, |
| 50 | Unspecified: true, |
| 51 | }, |
| 52 | ) |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | // Git copies through aliases as well as |
| 57 | // expanding them. |
| 58 | resultLine.attrs = append( |
| 59 | resultLine.attrs, |
| 60 | attr, |
| 61 | ) |
| 62 | } |
| 63 | result = append(result, resultLine) |
| 64 | case MacroLine: |
| 65 | if readMacros { |
| 66 | mp.macros[l.Macro()] = l.Attrs() |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | mp.didReadMacros = mp.didReadMacros || readMacros |
| 71 | return result |
| 72 | } |
| 73 | |
| 74 | // ProcessMacros reads all the lines but only processes macro lines. |
| 75 | func (mp *MacroProcessor) ProcessMacros(lines []Line) { |
| 76 | for _, line := range lines { |
| 77 | switch l := line.(type) { |
| 78 | case MacroLine: |
| 79 | mp.macros[l.Macro()] = l.Attrs() |
| 80 | default: |
| 81 | continue |
| 82 | } |
| 83 | } |
| 84 | mp.didReadMacros = true |
| 85 | } |