-
Notifications
You must be signed in to change notification settings - Fork 0
/
buildifier.go
233 lines (205 loc) · 6.76 KB
/
buildifier.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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
/*
Copyright 2017 The Kubernetes Authors.
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.
*/
// buildifier defines a Prow plugin that runs buildifier over modified BUILD,
// WORKSPACE, and skylark (.bzl) files in pull requests.
package buildifier
import (
"bytes"
"fmt"
"io/ioutil"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
"github.com/bazelbuild/buildtools/build"
"github.com/sirupsen/logrus"
"k8s.io/test-infra/prow/genfiles"
"k8s.io/test-infra/prow/git"
"k8s.io/test-infra/prow/github"
"k8s.io/test-infra/prow/pluginhelp"
"k8s.io/test-infra/prow/plugins"
)
const (
pluginName = "buildifier"
maxComments = 20
)
var buildifyRe = regexp.MustCompile(`(?mi)^/buildif(y|ier)\s*$`)
func init() {
plugins.RegisterGenericCommentHandler(pluginName, handleGenericComment, nil)
}
func helpProvider(config *plugins.Configuration, enabledRepos []string) (*pluginhelp.PluginHelp, error) {
// The Config field is omitted because this plugin is not configurable.
pluginHelp := &pluginhelp.PluginHelp{
Description: "The buildifier plugin runs buildifier on changes made to Bazel files in a PR. It then creates a new review on the pull request and leaves warnings at the appropriate lines of code.",
}
pluginHelp.AddCommand(pluginhelp.Command{
Usage: "/buildif(y|ier)",
Featured: false,
Description: "Runs buildifier on changes made to Bazel files in a PR",
WhoCanUse: "Anyone can trigger this command on a PR.",
Examples: []string{"/buildify", "/buildifier"},
})
return pluginHelp, nil
}
type githubClient interface {
GetFile(org, repo, filepath, commit string) ([]byte, error)
GetPullRequest(org, repo string, number int) (*github.PullRequest, error)
GetPullRequestChanges(org, repo string, number int) ([]github.PullRequestChange, error)
CreateReview(org, repo string, number int, r github.DraftReview) error
ListPullRequestComments(org, repo string, number int) ([]github.ReviewComment, error)
}
func handleGenericComment(pc plugins.PluginClient, e github.GenericCommentEvent) error {
return handle(pc.GitHubClient, pc.GitClient, pc.Logger, &e)
}
// modifiedBazelFiles returns a map from filename to patch string for all Bazel files
// that are modified in the PR.
func modifiedBazelFiles(ghc githubClient, org, repo string, number int, sha string) (map[string]string, error) {
changes, err := ghc.GetPullRequestChanges(org, repo, number)
if err != nil {
return nil, err
}
gfg, err := genfiles.NewGroup(ghc, org, repo, sha)
if err != nil {
return nil, err
}
modifiedFiles := make(map[string]string)
for _, change := range changes {
switch {
case gfg.Match(change.Filename):
continue
case change.Status == github.PullRequestFileRemoved || change.Status == github.PullRequestFileRenamed:
continue
// This also happens to match BUILD.bazel.
case strings.Contains(change.Filename, "BUILD"):
break
case strings.Contains(change.Filename, "WORKSPACE"):
break
case filepath.Ext(change.Filename) != ".bzl":
continue
}
modifiedFiles[change.Filename] = change.Patch
}
return modifiedFiles, nil
}
func uniqProblems(problems []string) []string {
sort.Strings(problems)
var uniq []string
last := ""
for _, s := range problems {
if s != last {
last = s
uniq = append(uniq, s)
}
}
return uniq
}
// problemsInFiles runs buildifier on the files. It returns a map from the file to
// a list of problems with that file.
func problemsInFiles(r *git.Repo, files map[string]string) (map[string][]string, error) {
problems := make(map[string][]string)
for f := range files {
src, err := ioutil.ReadFile(filepath.Join(r.Dir, f))
if err != nil {
return nil, err
}
// This is modeled after the logic from buildifier:
// https://github.com/bazelbuild/buildtools/blob/8818289/buildifier/buildifier.go#L261
content, err := build.Parse(f, src)
if err != nil {
return nil, fmt.Errorf("parsing as Bazel file %v", err)
}
beforeRewrite := build.Format(content)
var info build.RewriteInfo
build.Rewrite(content, &info)
ndata := build.Format(content)
if !bytes.Equal(src, ndata) && !bytes.Equal(src, beforeRewrite) {
// TODO(mattmoor): This always seems to be empty?
problems[f] = uniqProblems(info.Log)
}
}
return problems, nil
}
func handle(ghc githubClient, gc *git.Client, log *logrus.Entry, e *github.GenericCommentEvent) error {
// Only handle open PRs and new requests.
if e.IssueState != "open" || !e.IsPR || e.Action != github.GenericCommentActionCreated {
return nil
}
if !buildifyRe.MatchString(e.Body) {
return nil
}
org := e.Repo.Owner.Login
repo := e.Repo.Name
pr, err := ghc.GetPullRequest(org, repo, e.Number)
if err != nil {
return err
}
// List modified files.
modifiedFiles, err := modifiedBazelFiles(ghc, org, repo, pr.Number, pr.Head.SHA)
if err != nil {
return err
}
if len(modifiedFiles) == 0 {
return nil
}
log.Infof("Will buildify %d modified Bazel files.", len(modifiedFiles))
// Clone the repo, checkout the PR.
startClone := time.Now()
r, err := gc.Clone(e.Repo.FullName)
if err != nil {
return err
}
defer func() {
if err := r.Clean(); err != nil {
log.WithError(err).Error("Error cleaning up repo.")
}
}()
if err := r.CheckoutPullRequest(e.Number); err != nil {
return err
}
finishClone := time.Now()
log.WithField("duration", time.Since(startClone)).Info("Cloned and checked out PR.")
// Compute buildifier errors.
problems, err := problemsInFiles(r, modifiedFiles)
if err != nil {
return err
}
log.WithField("duration", time.Since(finishClone)).Info("Buildified.")
// Make the list of comments.
var comments []github.DraftReviewComment
for f := range problems {
comments = append(comments, github.DraftReviewComment{
Path: f,
// TODO(mattmoor): Include the messages if they are ever non-empty.
Body: strings.Join([]string{
"This Bazel file needs formatting, run:",
"```shell",
fmt.Sprintf("buildifier -mode=fix %q", f),
"```"}, "\n"),
Position: 1,
})
}
// Trim down the number of comments if necessary.
totalProblems := len(problems)
// Make the review body.
s := "s"
if totalProblems == 1 {
s = ""
}
response := fmt.Sprintf("%d warning%s.", totalProblems, s)
return ghc.CreateReview(org, repo, e.Number, github.DraftReview{
Body: plugins.FormatResponseRaw(e.Body, e.HTMLURL, e.User.Login, response),
Action: github.Comment,
Comments: comments,
})
}