generated from dogmatiq/template-go
/
hook.go
122 lines (104 loc) 路 2.54 KB
/
hook.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 web
import (
"context"
"fmt"
"net/http"
"github.com/dogmatiq/browser/analyzer"
"github.com/gin-gonic/gin"
"github.com/google/go-github/v38/github"
)
func handleGitHubHook(
version string,
secret string,
o *analyzer.Orchestrator,
) gin.HandlerFunc {
secretBytes := []byte(secret)
return func(ctx *gin.Context) {
payload, err := github.ValidatePayload(ctx.Request, secretBytes)
if err != nil {
renderError(ctx, version, http.StatusForbidden)
return
}
hookType := github.WebHookType(ctx.Request)
event, err := github.ParseWebHook(hookType, payload)
if err != nil {
renderError(ctx, version, http.StatusBadRequest)
return
}
if err := handleGitHubEvent(ctx, o, event); err != nil {
renderError(ctx, version, http.StatusInternalServerError)
fmt.Println("unable to handle event", err) // TODO
return
}
ctx.Writer.WriteHeader(http.StatusNoContent)
}
}
func handleGitHubEvent(
ctx context.Context,
o *analyzer.Orchestrator,
event interface{},
) error {
// TODO: handle repository rename
switch event := event.(type) {
case *github.InstallationEvent:
return handleInstallationEvent(ctx, o, event)
case *github.InstallationRepositoriesEvent:
return handleInstallationRepositoriesEvent(ctx, o, event)
case *github.PushEvent:
return handlePushEvent(ctx, o, event)
}
return nil
}
func handleInstallationEvent(
ctx context.Context,
o *analyzer.Orchestrator,
event *github.InstallationEvent,
) error {
if event.Action == nil {
return nil
}
switch *event.Action {
case "created", "unsuspend", "new_permissions_accepted":
for _, r := range event.Repositories {
if err := o.EnqueueAnalyis(ctx, r.GetID()); err != nil {
return err
}
}
case "deleted", "suspend":
for _, r := range event.Repositories {
if err := o.EnqueueRemoval(ctx, r.GetID()); err != nil {
return err
}
}
}
return nil
}
func handleInstallationRepositoriesEvent(
ctx context.Context,
o *analyzer.Orchestrator,
event *github.InstallationRepositoriesEvent,
) error {
for _, r := range event.RepositoriesRemoved {
if err := o.EnqueueRemoval(ctx, r.GetID()); err != nil {
return err
}
}
for _, r := range event.RepositoriesAdded {
if err := o.EnqueueAnalyis(ctx, r.GetID()); err != nil {
return err
}
}
return nil
}
func handlePushEvent(
ctx context.Context,
o *analyzer.Orchestrator,
event *github.PushEvent,
) error {
repo := event.GetRepo()
defaultRef := "refs/heads/" + repo.GetDefaultBranch()
if event.GetRef() != defaultRef {
return nil
}
return o.EnqueueAnalyis(ctx, repo.GetID())
}