-
Notifications
You must be signed in to change notification settings - Fork 4
/
rule.go
122 lines (100 loc) · 2.5 KB
/
rule.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package generate
import (
"github.com/please-build/buildtools/build"
"github.com/please-build/puku/edit"
"github.com/please-build/puku/kinds"
)
type rule struct {
dir string
kind *kinds.Kind
*build.Rule
}
// setOrDeleteAttr will make sure the attribute with the given name matches the values passed in. It will keep the
// existing expressions in the list to maintain things like comments.
func (rule *rule) setOrDeleteAttr(name string, values []string) {
if len(values) == 0 {
rule.DelAttr(name)
return
}
valuesMap := make(map[string]struct{})
for _, v := range values {
valuesMap[v] = struct{}{}
}
listExpr, _ := rule.Attr(name).(*build.ListExpr)
if listExpr == nil {
listExpr = &build.ListExpr{}
}
exprs := make([]build.Expr, 0, len(values))
done := map[string]struct{}{}
// Loop through the existing values, filtering out any that aren't supposed to be there
for _, expr := range listExpr.List {
val, ok := expr.(*build.StringExpr)
if !ok {
continue
}
if _, ok := valuesMap[val.Value]; ok {
exprs = append(exprs, val)
done[val.Value] = struct{}{}
}
}
// Loops through the value adding any new values that didn't used to be there
for _, v := range values {
if _, done := done[v]; !done {
exprs = append(exprs, edit.NewStringExpr(v))
}
}
listExpr.List = exprs
rule.SetAttr(name, listExpr)
}
func (rule *rule) isTest() bool {
return rule.kind.Type == kinds.Test
}
func (rule *rule) SrcsAttr() string {
return rule.kind.SrcsAttr
}
func (rule *rule) addSrc(src string) {
srcsAttr := rule.SrcsAttr()
srcs := rule.AttrStrings(srcsAttr)
rule.setOrDeleteAttr(srcsAttr, append(srcs, src))
}
func (rule *rule) removeSrc(rem string) {
srcsAttr := rule.SrcsAttr()
srcs := rule.AttrStrings(srcsAttr)
set := make([]string, 0, len(srcs))
for _, src := range srcs {
if src != rem {
set = append(set, src)
}
}
rule.setOrDeleteAttr(srcsAttr, set)
}
func (rule *rule) setExternal() {
rule.SetAttr("external", &build.Ident{Name: "True"})
}
func (rule *rule) localLabel() string {
return ":" + rule.Name()
}
func (rule *rule) label() string {
return BuildTarget(rule.Name(), rule.dir, "")
}
func (rule *rule) isExternal() bool {
if !rule.isTest() {
return false
}
external := rule.Attr("external")
if external == nil {
return false
}
ident, ok := external.(*build.Ident)
if !ok {
return false
}
return ident.Name == "True"
}
func newRule(r *build.Rule, kindType *kinds.Kind, pkgDir string) *rule {
return &rule{
dir: pkgDir,
kind: kindType,
Rule: r,
}
}