forked from bazelbuild/rules_go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
merger.go
195 lines (173 loc) · 4.42 KB
/
merger.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
/* Copyright 2016 The Bazel Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package merger provides methods for merging parsed BUILD files.
package merger
import (
"fmt"
"io/ioutil"
"os"
"sort"
"strings"
bzl "github.com/bazelbuild/buildifier/core"
)
const keep = "# keep" // marker in srcs or deps to tell gazelle to preserve.
var (
mergeableFields = map[string]bool{
"srcs": true,
"deps": true,
}
)
// MergeWithExisting looks for an existing BUILD file at file.Path
// loads it, and attempts to merge elements of newfile into it.
// returns newfile, nil if FileNotExists
func MergeWithExisting(newfile *bzl.File) (*bzl.File, error) {
b, err := ioutil.ReadFile(newfile.Path)
if err != nil {
if os.IsNotExist(err) {
return newfile, nil
}
return nil, err
}
f, err := bzl.Parse(newfile.Path, b)
if err != nil {
return nil, err
}
var newStmt []bzl.Expr
for _, s := range newfile.Stmt {
c, ok := s.(*bzl.CallExpr)
if !ok {
return nil, fmt.Errorf("got %v expected only CallExpr in %q", s, newfile.Path)
}
other, err := match(f, c)
if err != nil {
return nil, err
}
if other == nil {
newStmt = append(newStmt, c)
continue
}
if name(c) == "load" {
mergeLoad(c, other, f)
} else {
merge(c, other)
}
}
f.Stmt = append(f.Stmt, newStmt...)
return f, nil
}
// merge takes new info from src and merges into dest.
// pre: these calls are the same X and 'name'
func merge(src, dest *bzl.CallExpr) {
destRule := &bzl.Rule{dest}
srcRule := &bzl.Rule{src}
for _, k := range srcRule.AttrKeys() {
if !mergeableFields[k] {
continue
}
keepIfRequested(srcRule.Attr(k), destRule.Attr(k))
destRule.SetAttr(k, srcRule.Attr(k))
}
}
// keepIfRequested takes two ListExpr and looks for any '# keep' suffixes in discard to preserve
func keepIfRequested(replace, discard bzl.Expr) {
r, ok := replace.(*bzl.ListExpr)
if !ok {
return
}
d, ok := discard.(*bzl.ListExpr)
if !ok {
return
}
for _, v := range d.List {
c := v.Comment()
if len(c.Suffix) == 0 {
continue
}
if strings.HasPrefix(c.Suffix[0].Token, keep) {
r.List = append(r.List, v)
}
}
}
func mergeLoad(src, dest *bzl.CallExpr, oldfile *bzl.File) {
vals := make(map[string]bzl.Expr)
for _, v := range src.List[1:] {
vals[stringValue(v)] = v
}
for _, v := range dest.List[1:] {
rule := stringValue(v)
if _, ok := vals[rule]; !ok && ruleUsed(rule, oldfile) {
vals[rule] = v
}
}
keys := make([]string, 0, len(vals))
for k := range vals {
keys = append(keys, k)
}
sort.Strings(keys)
dest.List = dest.List[:1]
for _, k := range keys {
dest.List = append(dest.List, vals[k])
}
}
func ruleUsed(rule string, oldfile *bzl.File) bool {
return len(oldfile.Rules(rule)) != 0
}
// match looks for the matching CallExpr in f using X and name
// i.e. two 'go_library(name = "foo", ...)' are considered matches
// despite the values of the other fields.
// exception: if c is a 'load' statement, the match is done on the first value.
func match(f *bzl.File, c *bzl.CallExpr) (*bzl.CallExpr, error) {
var m matcher
if x := name(c); x == "load" {
if len(c.List) == 0 {
return nil, nil
}
m = &loadMatcher{stringValue(c.List[0])}
} else {
m = &nameMatcher{x, (&bzl.Rule{c}).AttrString("name")}
}
for _, s := range f.Stmt {
other, ok := s.(*bzl.CallExpr)
if !ok {
continue
}
if m.match(other) {
return other, nil
}
}
return nil, nil
}
type matcher interface {
match(c *bzl.CallExpr) bool
}
type nameMatcher struct {
x, name string
}
func (m *nameMatcher) match(c *bzl.CallExpr) bool {
return m.x == name(c) && m.name == (&bzl.Rule{c}).AttrString("name")
}
type loadMatcher struct {
load string
}
func (m *loadMatcher) match(c *bzl.CallExpr) bool {
return name(c) == "load" && len(c.List) > 0 && m.load == stringValue(c.List[0])
}
func name(c *bzl.CallExpr) string {
return (&bzl.Rule{c}).Kind()
}
func stringValue(e bzl.Expr) string {
s, ok := e.(*bzl.StringExpr)
if !ok {
return ""
}
return s.Value
}