...
1 package bulldozesynclabel
2
3 import (
4 "fmt"
5 "strconv"
6 "strings"
7
8 "github.com/google/go-github/v47/github"
9
10 "edge-infra.dev/pkg/f8n/devinfra/jack/constants"
11 "edge-infra.dev/pkg/f8n/devinfra/jack/plugin"
12 )
13
14 func init() {
15 plugin.RegisterStatusEventHandler(constants.PluginApprovedLabel, handleStatusEvent)
16 }
17
18 func handleStatusEvent(hp plugin.HandlerParams, se github.StatusEvent) {
19 hp.Log.WithName(constants.PluginApprovedLabel)
20
21
22 if se.GetContext() != "mergeable: master" {
23 return
24 }
25 hp.Log.Info("Running approved_label")
26 hp.Log.Info("found a policybot status event")
27
28
29
30
31 prArr := strings.Split(se.GetTargetURL(), "/")
32
33
34 prStr := prArr[len(prArr)-1]
35
36
37 prNum, err := strconv.Atoi(prStr)
38 if err != nil {
39 hp.Log.Error(err, "Failed to get PR number")
40 return
41 }
42
43
44 pr, _, err := hp.Client.PullRequests().Get(hp.Ctx, hp.Org, hp.Repo, prNum)
45 if err != nil {
46 hp.Log.Error(err, "Failed to retrieve PR")
47 return
48 }
49
50
51 hasOK := hasApproved(pr.Labels)
52 hasDoNotMerge := hasDoNotMerge(pr.Labels)
53
54
55 if pr.GetDraft() && hasOK {
56 hp.Log.Info(fmt.Sprintf("PR #%d is a draft. Attempting to remove %s", prNum, constants.Approved))
57 removeSyncLabel(hp, prNum)
58 return
59 }
60
61
62 if hasDoNotMerge && hasOK {
63 hp.Log.Info(fmt.Sprintf("Cannot sync while %s is present. Attempting to remove %s", constants.DoNotMerge, constants.Approved))
64 removeSyncLabel(hp, prNum)
65 return
66 }
67
68
69 state := se.GetState()
70 switch {
71 case state == "success" && !hasOK:
72 addLabel(hp, prNum)
73 case (state == "pending" || state == "failure") && hasOK:
74 removeSyncLabel(hp, prNum)
75 }
76 }
77
78 func hasApproved(labels []*github.Label) bool {
79 for _, label := range labels {
80 if label.GetName() == constants.Approved {
81 return true
82 }
83 }
84 return false
85 }
86
87 func hasDoNotMerge(labels []*github.Label) bool {
88 for _, label := range labels {
89 if label.GetName() == constants.DoNotMerge {
90 return true
91 }
92 }
93 return false
94 }
95
96 func addLabel(hp plugin.HandlerParams, num int) {
97 hp.Log.Info(fmt.Sprintf("adding %s", constants.Approved))
98
99 labels := []string{constants.Approved}
100 _, _, err := hp.Client.Issues().AddLabelsToIssue(hp.Ctx, hp.Org, hp.Repo, num, labels)
101 if err != nil {
102 hp.Log.Error(err, fmt.Sprintf("Failed to add %s", constants.Approved))
103 }
104 }
105
106 func removeSyncLabel(hp plugin.HandlerParams, num int) {
107 hp.Log.Info(fmt.Sprintf("removing %s", constants.Approved))
108
109 _, err := hp.Client.Issues().RemoveLabelForIssue(hp.Ctx, hp.Org, hp.Repo, num, constants.Approved)
110 if err != nil {
111 hp.Log.Error(err, fmt.Sprintf("Failed to remove %s", constants.Approved))
112 }
113 }
114
View as plain text