This repository has been archived by the owner on Nov 9, 2021. It is now read-only.
forked from maubot/gitlab
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgitlab-webhook.go
306 lines (277 loc) · 8 KB
/
gitlab-webhook.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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
// maulabbot - A Gitlab bot for Matrix
// Copyright (C) 2017 Tulir Asokan
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package main
import (
"bytes"
"fmt"
"net/http"
"strings"
"time"
"gopkg.in/go-playground/webhooks.v5/gitlab"
"maunium.net/go/mautrix"
)
func handlePayload(hook *gitlab.Webhook) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
payload, err := hook.Parse(
r,
gitlab.PushEvents,
gitlab.TagEvents,
gitlab.IssuesEvents,
gitlab.CommentEvents,
gitlab.MergeRequestEvents,
gitlab.PipelineEvents,
//gitlab.ConfidentialIssuesEvents,
//gitlab.WikiPageEvents,
//gitlab.BuildEvents,
)
if err != nil {
if err == gitlab.ErrEventNotFound {
w.WriteHeader(500)
w.Write([]byte("Event not found"))
return
}
}
roomID := r.URL.Query().Get("room")
if len(roomID) == 0 {
w.WriteHeader(400)
w.Write([]byte("No room specified."))
return
}
room := mxbot.GetRoom(roomID)
switch payload.(type) {
case gitlab.PushEventPayload:
handlePushEvent(payload, *room)
case gitlab.TagEventPayload:
handleTagEvent(payload, *room)
case gitlab.IssueEventPayload:
handleIssueEvent(payload, *room)
case gitlab.CommentEventPayload:
handleCommentEvent(payload, *room)
case gitlab.MergeRequestEventPayload:
handleMergeRequestEvent(payload, *room)
case gitlab.PipelineEventPayload:
handlePipelineEvent(payload, *room)
case gitlab.WikiPageEventPayload:
handleWikiPageEvent(payload, *room)
//case gitlab.ConfidentialIssueEventPayload:
//case gitlab.BuildEventPayload:
}
w.WriteHeader(204)
return
}
}
func startWebhook() func() {
hook, _ := gitlab.New(gitlab.Options.Secret(config.Webhook.Secret))
server := &http.Server{Addr: config.Webhook.Listen}
go func() {
mux := http.NewServeMux()
mux.Handle(config.Webhook.Path, http.HandlerFunc(handlePayload(hook)))
server.Handler = mux
fmt.Println("Listening to GitLab webhooks at", config.Webhook.Listen+config.Webhook.Path)
err := server.ListenAndServe()
if err != nil {
fmt.Println(err)
}
}()
return func() {
server.Shutdown(nil)
}
}
func handlePushEvent(payload interface{}, room mautrix.Room) {
data := payload.(gitlab.PushEventPayload)
branch := strings.TrimPrefix(data.Ref, "refs/heads/")
if data.TotalCommitsCount == 0 {
room.SendfHTML(
"[%[3]s/%[4]s] %[5]s force pushed to or deleted branch <a href='%[1]s/tree/%[2]s'>%[2]s</a>",
data.Project.WebURL,
branch,
data.Project.Namespace,
data.Project.Name,
data.UserName)
return
}
var pluralizer = ""
if data.TotalCommitsCount != 1 {
pluralizer = "s"
}
room.SendfHTML(
"[<a href='%[1]s/tree/%[2]s'>%[3]s/%[4]s#%[2]s</a>] %[5]d new commit%[7]s by %[6]s",
data.Project.WebURL,
branch,
data.Project.Namespace,
data.Project.Name,
data.TotalCommitsCount,
data.UserName,
pluralizer)
// IRC compatibility: Allow up to 4 commits to be displayed through the IRC bridge without
// having the bridge turn the message into a link.
if data.TotalCommitsCount > 4 || !config.Options.IRCCompatibility {
var msg bytes.Buffer
fmt.Fprint(&msg, "<ul>")
for i := len(data.Commits) - 1; i >= 0; i-- {
commit := data.Commits[i]
lines := strings.Split(commit.Message, "\n")
message := lines[0]
if len(lines) > 1 && len(strings.Join(lines[1:], "")) > 0 {
message += " (...)"
}
fmt.Fprintf(&msg, "<li>%s (%s)</li>\n", message, commit.ID[:8])
}
fmt.Fprint(&msg, "</ul>")
room.SendHTML(msg.String())
} else {
for i := len(data.Commits) - 1; i >= 0; i-- {
commit := data.Commits[i]
lines := strings.Split(commit.Message, "\n")
message := lines[0]
if len(lines) > 1 && len(strings.Join(lines[1:], "")) > 0 {
message += " (...)"
}
room.SendfHTML("<ul><li>%s (%s)</li></ul>", message, commit.ID[:8])
}
}
}
func handleTagEvent(payload interface{}, room mautrix.Room) {
data := payload.(gitlab.TagEventPayload)
if data.ObjectKind != "tag_push" {
return
}
tag := strings.TrimPrefix(data.Ref, "refs/tags/")
room.SendfHTML("[%[1]s/%[2]s] %[3]s created tag <a href='%[4]s/tags/%[5]s'>%[5]s</a>",
data.Project.Namespace,
data.Project.Name,
data.UserName,
data.Project.WebURL,
tag)
}
func handleIssueEvent(payload interface{}, room mautrix.Room) {
data, ok := payload.(gitlab.IssueEventPayload)
confidential := ""
if !ok {
data2, ok := payload.(gitlab.ConfidentialIssueEventPayload)
if !ok {
fmt.Println("Unexpected error: Received issue event with incorrect payload type.")
return
}
confidential = "confidential "
data = data2.IssueEventPayload
}
action := data.ObjectAttributes.Action
if action == "update" || len(action) == 0 {
return
} else if !strings.HasSuffix(action, "e") {
action += "e"
}
room.SendfHTML(
"[%[1]s/%[2]s] %[3]s %[4]sd %[5]sissue <a href='%[6]s'>%[7]s (#%[8]d)</a>",
data.Project.Namespace,
data.Project.Name,
data.User.Name,
action,
confidential,
data.ObjectAttributes.URL,
data.ObjectAttributes.Title,
data.ObjectAttributes.IID)
}
func handleMergeRequestEvent(payload interface{}, room mautrix.Room) {
data := payload.(gitlab.MergeRequestEventPayload)
action := data.ObjectAttributes.Action
if action == "update" {
return
} else if !strings.HasSuffix(action, "e") {
action += "e"
}
room.SendfHTML(
"[%[1]s/%[2]s] %[3]s %[4]sd merge request <a href='%[5]s'>%[6]s (!%[7]d)</a>",
data.ObjectAttributes.Target.Namespace,
data.ObjectAttributes.Target.Name,
data.User.Name,
action,
data.ObjectAttributes.URL,
data.ObjectAttributes.Title,
data.ObjectAttributes.IID)
}
func handleCommentEvent(payload interface{}, room mautrix.Room) {
data := payload.(gitlab.CommentEventPayload)
var notebookType, title string
var notebookIdentifier rune
var id int64
switch data.ObjectAttributes.NotebookType {
case "Issue":
notebookType = "issue"
notebookIdentifier = '#'
title = data.Issue.Title
id = data.Issue.IID
case "MergeRequest":
notebookType = "merge request"
notebookIdentifier = '!'
title = data.MergeRequest.Title
id = data.MergeRequest.IID
}
room.SendfHTML(
"[%[1]s/%[2]s] %[3]s <a href='%[5]s'>commented</a> on %[4]s %[6]s (%[8]c%[7]d)",
data.Project.Namespace,
data.Project.Name,
data.User.Name,
notebookType,
data.ObjectAttributes.URL,
title,
id,
notebookIdentifier)
}
func handlePipelineEvent(payload interface{}, room mautrix.Room) {
data := payload.(gitlab.PipelineEventPayload)
var pluralizer = ""
if len(data.Builds) != 1 {
pluralizer = "s"
}
duration := fmt.Sprintf("%ds", data.ObjectAttributes.Duration)
if d, err := time.ParseDuration(duration); err == nil {
duration = d.String()
}
room.SendfHTML(
"[%[1]s/%[2]s] %[3]d pipeline%[4]s complete in %[5]s",
data.Project.Namespace,
data.Project.Name,
len(data.Builds),
pluralizer,
duration)
for _, b := range data.Builds {
room.SendfHTML(
"<ul><li><a href='%[1]s/-/jobs/%[2]d'>%[3]s:%[4]s (%[2]d)</a> %[5]s</li></ul>",
data.Project.WebURL,
b.ID,
b.Name,
b.Stage,
b.Status)
}
}
func handleWikiPageEvent(payload interface{}, room mautrix.Room) {
data := payload.(gitlab.WikiPageEventPayload)
action := data.ObjectAttributes.Action
if !strings.HasSuffix(action, "e") {
action += "e"
}
room.SendfHTML(
"[%[1]s/%[2]s] %[3]s %[4]sd page on wiki <a href='%[5]s'>%[6]s (#%[7]d)</a>",
data.Project.Namespace,
data.Project.Name,
data.User.Name,
action,
data.ObjectAttributes.URL,
data.ObjectAttributes.Title,
data.ObjectAttributes.IID)
}