-
Notifications
You must be signed in to change notification settings - Fork 104
/
approve.go
275 lines (227 loc) · 6.69 KB
/
approve.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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
// Copyright 2018 Palantir Technologies, Inc.
//
// 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 approval
import (
"context"
"fmt"
"sort"
"strings"
"time"
"github.com/pkg/errors"
"github.com/rs/zerolog"
"github.com/palantir/policy-bot/policy/common"
"github.com/palantir/policy-bot/pull"
)
type Rule struct {
Name string `yaml:"name"`
Predicates Predicates `yaml:"if"`
Options Options `yaml:"options"`
Requires Requires `yaml:"requires"`
}
type Options struct {
AllowAuthor bool `yaml:"allow_author"`
AllowContributor bool `yaml:"allow_contributor"`
InvalidateOnPush bool `yaml:"invalidate_on_push"`
IgnoreUpdateMerges bool `yaml:"ignore_update_merges"`
Methods *common.Methods `yaml:"methods"`
}
func (opts *Options) GetMethods() *common.Methods {
methods := opts.Methods
if methods == nil {
methods = &common.Methods{
Comments: []string{
":+1:",
"👍",
},
GithubReview: true,
}
}
methods.GithubReviewState = pull.ReviewApproved
return methods
}
type Requires struct {
Count int `yaml:"count"`
common.Actors `yaml:",inline"`
}
func (r *Rule) Evaluate(ctx context.Context, prctx pull.Context) (res common.Result) {
log := zerolog.Ctx(ctx)
res.Name = r.Name
res.Status = common.StatusSkipped
for _, p := range r.Predicates.Predicates() {
satisfied, desc, err := p.Evaluate(ctx, prctx)
if err != nil {
res.Error = errors.Wrap(err, "failed to evaluate predicate")
return
}
if !satisfied {
log.Debug().Msgf("skipping rule, predicate of type %T was not satisfied", p)
res.Description = desc
if desc == "" {
res.Description = "The preconditions of this rule are not satisfied"
}
return
}
}
approved, msg, err := r.IsApproved(ctx, prctx)
if err != nil {
res.Error = errors.Wrap(err, "failed to compute approval status")
return
}
res.Description = msg
if approved {
res.Status = common.StatusApproved
} else {
res.Status = common.StatusPending
}
return
}
func (r *Rule) IsApproved(ctx context.Context, prctx pull.Context) (bool, string, error) {
log := zerolog.Ctx(ctx)
if r.Requires.Count <= 0 {
log.Debug().Msg("rule requires no approvals")
return true, "No approval required", nil
}
candidates, err := r.Options.GetMethods().Candidates(ctx, prctx)
if err != nil {
return false, "", errors.Wrap(err, "failed to get approval candidates")
}
sort.Stable(common.CandidatesByCreationTime(candidates))
if r.Options.InvalidateOnPush {
commits, err := r.filteredCommits(prctx)
if err != nil {
return false, "", err
}
last := findLastPushed(commits)
if last == nil {
return false, "", errors.New("no commit contained a push date")
}
var allowedCandidates []*common.Candidate
for _, candidate := range candidates {
if candidate.CreatedAt.After(*last.PushedAt) {
allowedCandidates = append(allowedCandidates, candidate)
}
}
log.Debug().Msgf("discarded %d candidates invalidated by push of %s at %s",
len(candidates)-len(allowedCandidates),
last.SHA,
last.PushedAt.Format(time.RFC3339))
candidates = allowedCandidates
}
log.Debug().Msgf("found %d candidates for approval", len(candidates))
// collect users "banned" by approval options
banned := make(map[string]bool)
// "author" is the user who opened the PR
// if contributors are allowed, the author counts as a contributor
author := prctx.Author()
if !r.Options.AllowAuthor && !r.Options.AllowContributor {
banned[author] = true
}
// "contributor" is any user who added a commit to the PR
if !r.Options.AllowContributor {
commits, err := r.filteredCommits(prctx)
if err != nil {
return false, "", err
}
for _, c := range commits {
for _, u := range c.Users() {
if u != author {
banned[u] = true
}
}
}
}
// filter real approvers using banned status and required membership
var approvers []string
for _, c := range candidates {
if banned[c.User] {
log.Debug().Str("user", c.User).Msg("rejecting approval by banned user")
continue
}
isApprover, err := r.Requires.IsActor(ctx, prctx, c.User)
if err != nil {
return false, "", errors.Wrap(err, "failed to check candidate status")
}
if !isApprover {
log.Debug().Str("user", c.User).Msg("ignoring approval by non-whitelisted user")
continue
}
approvers = append(approvers, c.User)
}
log.Debug().Msgf("found %d/%d required approvers", len(approvers), r.Requires.Count)
remaining := r.Requires.Count - len(approvers)
if remaining <= 0 {
msg := fmt.Sprintf("Approved by %s", strings.Join(approvers, ", "))
return true, msg, nil
}
if len(candidates) > 0 && len(approvers) == 0 {
msg := fmt.Sprintf("%d/%d approvals required. Ignored %s from disqualified users",
len(approvers),
r.Requires.Count,
numberOfApprovals(len(candidates)))
return false, msg, nil
}
msg := fmt.Sprintf("%d/%d approvals required", len(approvers), r.Requires.Count)
return false, msg, nil
}
func (r *Rule) filteredCommits(prctx pull.Context) ([]*pull.Commit, error) {
commits, err := prctx.Commits()
if err != nil {
return nil, errors.Wrap(err, "failed to list commits")
}
needsFiltering := r.Options.IgnoreUpdateMerges
if !needsFiltering {
return commits, nil
}
var filtered []*pull.Commit
for _, c := range commits {
switch {
case isUpdateMerge(commits, c):
default:
filtered = append(filtered, c)
}
}
return filtered, nil
}
func isUpdateMerge(commits []*pull.Commit, c *pull.Commit) bool {
// must be a simple merge commit (exactly 2 parents)
if len(c.Parents) != 2 {
return false
}
// must be created via the UI or the API (no local merges)
if !c.CommittedViaWeb {
return false
}
shas := make(map[string]bool)
for _, c := range commits {
shas[c.SHA] = true
}
// first parent must exist: it is a commit on the head branch
// second parent must not exist: it is already in the base branch
return shas[c.Parents[0]] && !shas[c.Parents[1]]
}
func findLastPushed(commits []*pull.Commit) *pull.Commit {
var last *pull.Commit
for _, c := range commits {
if c.PushedAt != nil && (last == nil || c.PushedAt.After(*last.PushedAt)) {
last = c
}
}
return last
}
func numberOfApprovals(count int) string {
if count == 1 {
return "1 approval"
}
return fmt.Sprintf("%d approvals", count)
}