BlueGit

timfa bluegit

Files

bluegit / internal / webhook / payload.go

payload.go

payload.go 13.8 KiB Download Raw
1package webhook
2
3import (
4 "encoding/json"
5 "strings"
6
7 "gitlab.com/Timfa/bluegit/internal/ci"
8)
9
10// Grenzen voor wat een webhook van een gefaalde job meestuurt.
11const (
12 LogMaxLines = 200
13 LogMaxBytes = 64 << 10
14)
15
16// MaxPushCommits is het aantal commits in een push-payload.
17// Dat zijn de nieuwste in het bereik, oudste eerst.
18const MaxPushCommits = 20
19
20// Document is de JSON-body van een webhook zonder eigen sjabloon.
21type Document struct {
22 ObjectKind string `json:"object_kind"`
23 Type string `json:"type"`
24 EventName string `json:"event_name"`
25 Project string `json:"project"`
26 Group string `json:"group,omitempty"`
27 Actor string `json:"actor,omitempty"`
28 Summary string `json:"summary,omitempty"`
29 URL string `json:"url,omitempty"`
30 Branch string `json:"branch,omitempty"`
31 Commit string `json:"commit,omitempty"`
32 PipelineID string `json:"pipeline_id,omitempty"`
33 ReleaseTag string `json:"release_tag,omitempty"`
34
35 Pipeline *PipelineInfo `json:"pipeline,omitempty"`
36 Jobs *[]JobInfo `json:"jobs,omitempty"`
37
38 Ref string `json:"ref,omitempty"`
39 Before string `json:"before,omitempty"`
40 After string `json:"after,omitempty"`
41 Commits *[]CommitInfo `json:"commits,omitempty"`
42
43 MergeRequest *MRInfo `json:"merge_request,omitempty"`
44 Comment string `json:"comment,omitempty"`
45
46 Release *ReleaseInfo `json:"release,omitempty"`
47 Issue *IssueInfo `json:"issue,omitempty"`
48 Note *NoteInfo `json:"note,omitempty"`
49}
50
51// NoteInfo is een reactie op een issue of merge request.
52type NoteInfo struct {
53 Body string `json:"body"`
54 NoteableType string `json:"noteable_type"`
55 NoteableID int64 `json:"noteable_id"`
56 Author string `json:"author"`
57 URL string `json:"url"`
58}
59
60// PipelineInfo is de pipeline waar het event over gaat.
61type PipelineInfo struct {
62 ID int64 `json:"id"`
63 Status string `json:"status"`
64 Ref string `json:"ref"`
65 SHA string `json:"sha"`
66 CommitMessage string `json:"commit_message"`
67 Author string `json:"author"`
68 Duration float64 `json:"duration"`
69 URL string `json:"url,omitempty"`
70}
71
72// JobInfo is één job in een pipeline-event.
73// Elke job stuurt de console-output mee. log_url staat er alleen als de log
74// is afgekapt, en wijst naar de API voor de volledige tekst.
75type JobInfo struct {
76 Name string `json:"name"`
77 Stage string `json:"stage"`
78 Status string `json:"status"`
79 Duration float64 `json:"duration"`
80 AllowFailure bool `json:"allow_failure"`
81 WebURL string `json:"web_url"`
82 Log string `json:"log"`
83 LogTruncated bool `json:"log_truncated"`
84 LogURL string `json:"log_url,omitempty"`
85 // CancelReason is superseded (nieuwere pipeline) of manual bij status canceled.
86 CancelReason string `json:"cancel_reason,omitempty"`
87 // FailureReason is bijv. job_execution_timeout bij status failed.
88 FailureReason string `json:"failure_reason,omitempty"`
89}
90
91// CommitInfo is één commit in een push of merge request.
92// Files noemt de wijzigingen. De difftekst zelf staat niet in de payload;
93// diff_url wijst naar de API die hem teruggeeft.
94type CommitInfo struct {
95 SHA string `json:"sha"`
96 Message string `json:"message"`
97 Author string `json:"author"`
98 Timestamp string `json:"timestamp"`
99 URL string `json:"url"`
100 Files []FileChange `json:"files"`
101 DiffURL string `json:"diff_url"`
102}
103
104// FileChange is één gewijzigd bestand, met status en regelaantallen.
105// Status is added, modified, removed of renamed.
106type FileChange struct {
107 Path string `json:"path"`
108 Status string `json:"status"`
109 PreviousPath string `json:"previous_path,omitempty"`
110 Additions int `json:"additions"`
111 Deletions int `json:"deletions"`
112 Binary bool `json:"binary,omitempty"`
113}
114
115// MRInfo is de merge request van het event.
116// DiffStats is de three-dot vergelijking. De difftekst staat op diff_url.
117type MRInfo struct {
118 ID int64 `json:"id"`
119 Number int64 `json:"number"`
120 Title string `json:"title"`
121 Description string `json:"description"`
122 SourceBranch string `json:"source_branch"`
123 TargetBranch string `json:"target_branch"`
124 Status string `json:"status"`
125 Author string `json:"author"`
126 Action string `json:"action"`
127 URL string `json:"url,omitempty"`
128 Reviewers []ReviewerInfo `json:"reviewers"`
129 Comments []CommentInfo `json:"comments"`
130 Commits []CommitInfo `json:"commits"`
131 DiffStats DiffStats `json:"diff_stats"`
132 DiffURL string `json:"diff_url"`
133}
134
135// ReviewerInfo is de huidige review van één persoon.
136type ReviewerInfo struct {
137 Username string `json:"username"`
138 Status string `json:"status"`
139}
140
141// CommentInfo is een reactie op de merge request.
142type CommentInfo struct {
143 ID int64 `json:"id"`
144 Author string `json:"author"`
145 Body string `json:"body"`
146 CreatedAt string `json:"created_at"`
147 FilePath string `json:"file_path,omitempty"`
148 LineStart int `json:"line_start,omitempty"`
149 LineEnd int `json:"line_end,omitempty"`
150 ParentID int64 `json:"parent_id,omitempty"`
151}
152
153// DiffStats telt de regels van de vergelijking, per bestand.
154type DiffStats struct {
155 Additions int `json:"additions"`
156 Deletions int `json:"deletions"`
157 Files []FileChange `json:"files"`
158}
159
160// IssueInfo is het issue van het event.
161// Action is opened, updated, closed, reopened of commented.
162type IssueInfo struct {
163 ID int64 `json:"id"`
164 Number int64 `json:"number"`
165 Title string `json:"title"`
166 Description string `json:"description"`
167 Status string `json:"status"`
168 Confidential bool `json:"confidential"`
169 Author string `json:"author"`
170 Assignees []string `json:"assignees"`
171 Labels []string `json:"labels"`
172 Milestone string `json:"milestone"`
173 DueDate string `json:"due_date"`
174 Action string `json:"action"`
175 URL string `json:"url,omitempty"`
176}
177
178// ReleaseInfo is een gepubliceerde release.
179type ReleaseInfo struct {
180 Tag string `json:"tag"`
181 Name string `json:"name"`
182 Commit string `json:"commit"`
183 Assets []AssetInfo `json:"assets"`
184}
185
186// AssetInfo is een bestand bij een release.
187type AssetInfo struct {
188 Name string `json:"name"`
189 URL string `json:"url"`
190 Size int64 `json:"size"`
191}
192
193// Document bouwt de JSON-structuur. Lege deelobjecten blijven weg.
194func (ev Event) Document() Document {
195 d := Document{
196 ObjectKind: objectKind(ev.Type),
197 Type: ev.Type,
198 Project: ev.Project,
199 Group: ev.Group,
200 Actor: ev.Actor,
201 Summary: ev.Summary,
202 URL: ev.URL,
203 Branch: ev.Branch,
204 Commit: ev.Commit,
205 PipelineID: ev.PipelineID,
206 ReleaseTag: ev.ReleaseTag,
207 Pipeline: ev.Pipeline,
208 Ref: ev.Ref,
209 Before: ev.Before,
210 After: ev.After,
211 MergeRequest: ev.MergeRequest,
212 Release: ev.Release,
213 Issue: ev.Issue,
214 }
215 d.EventName = Specific(ev)
216 if d.EventName == "" {
217 d.EventName = ev.Type
218 }
219 switch ev.Type {
220 case EventPush:
221 commits := ev.Commits
222 if commits == nil {
223 commits = []CommitInfo{}
224 }
225 for i := range commits {
226 if commits[i].Files == nil {
227 commits[i].Files = []FileChange{}
228 }
229 }
230 d.Commits = &commits
231 case EventPipelineSuccess, EventPipelineFailure:
232 jobs := ev.Jobs
233 if jobs == nil {
234 jobs = []JobInfo{}
235 }
236 d.Jobs = &jobs
237 case EventMergeRequest:
238 if ev.MergeRequest != nil {
239 mr := *ev.MergeRequest
240 if mr.Number == 0 {
241 mr.Number = mr.ID
242 }
243 if mr.Reviewers == nil {
244 mr.Reviewers = []ReviewerInfo{}
245 }
246 if mr.Comments == nil {
247 mr.Comments = []CommentInfo{}
248 }
249 if mr.Commits == nil {
250 mr.Commits = []CommitInfo{}
251 }
252 for i := range mr.Commits {
253 if mr.Commits[i].Files == nil {
254 mr.Commits[i].Files = []FileChange{}
255 }
256 }
257 if mr.DiffStats.Files == nil {
258 mr.DiffStats.Files = []FileChange{}
259 }
260 d.MergeRequest = &mr
261 if mr.Action == "commented" {
262 d.Comment = ev.Comment
263 d.Note = &NoteInfo{Body: ev.Comment, NoteableType: "MergeRequest", NoteableID: mr.ID, Author: ev.Actor, URL: firstNonEmpty(mr.URL, ev.URL)}
264 }
265 }
266 case EventIssue:
267 if ev.Issue != nil {
268 iss := *ev.Issue
269 if iss.Number == 0 {
270 iss.Number = iss.ID
271 }
272 if iss.Assignees == nil {
273 iss.Assignees = []string{}
274 }
275 if iss.Labels == nil {
276 iss.Labels = []string{}
277 }
278 d.Issue = &iss
279 if iss.Action == "commented" {
280 d.Comment = ev.Comment
281 d.Note = &NoteInfo{Body: ev.Comment, NoteableType: "Issue", NoteableID: iss.ID, Author: ev.Actor, URL: firstNonEmpty(iss.URL, ev.URL)}
282 }
283 }
284 }
285 if d.Release != nil && d.Release.Assets == nil {
286 rel := *d.Release
287 rel.Assets = []AssetInfo{}
288 d.Release = &rel
289 }
290 return d
291}
292
293func objectKind(eventType string) string {
294 switch eventType {
295 case EventPipelineSuccess, EventPipelineFailure:
296 return "pipeline"
297 case EventRelease:
298 return "release"
299 case EventMergeRequest:
300 return "merge_request"
301 default:
302 return eventType
303 }
304}
305
306// TailLog houdt de laatste LogMaxLines regels en hoogstens LogMaxBytes.
307// Geheimwaarden van minstens 8 tekens worden [MASKED], net als in de joblog.
308// truncated is true zodra er regels of bytes af zijn.
309func TailLog(text string, secrets []string) (string, bool) {
310 text = ci.Mask(text, secrets)
311 if text == "" {
312 return "", false
313 }
314 truncated := false
315 lines := strings.Split(text, "\n")
316 if len(lines) > LogMaxLines {
317 lines = lines[len(lines)-LogMaxLines:]
318 truncated = true
319 }
320 out := strings.Join(lines, "\n")
321 if len(out) > LogMaxBytes {
322 out = cutUTF8Tail(out, LogMaxBytes)
323 truncated = true
324 }
325 return out, truncated
326}
327
328func cutUTF8Tail(s string, max int) string {
329 if len(s) <= max {
330 return s
331 }
332 s = s[len(s)-max:]
333 for len(s) > 0 && s[0]&0xC0 == 0x80 {
334 s = s[1:]
335 }
336 return s
337}
338
339// Example is het voorbeeld op de infopagina.
340func Example() string {
341 samples := []Event{
342 {
343 Type: EventPipelineFailure, Project: "tim/app", Actor: "tim",
344 Summary: "pipeline #26 voor tim/app is mislukt",
345 URL: "https://git.example/tim/app/-/pipelines/26",
346 Branch: "master", Commit: "725e6947", PipelineID: "26",
347 Pipeline: &PipelineInfo{
348 ID: 26, Status: "failed", Ref: "refs/heads/master", SHA: "725e6947",
349 CommitMessage: "fix de build", Author: "tim", Duration: 12.4,
350 URL: "https://git.example/tim/app/-/pipelines/26",
351 },
352 Jobs: []JobInfo{
353 {
354 Name: "test", Stage: "test", Status: "failed", Duration: 4.1,
355 AllowFailure: false, WebURL: "https://git.example/tim/app/-/pipelines/26/jobs/7",
356 Log: "go: token [MASKED]\nFAIL", LogTruncated: true,
357 LogURL: "https://git.example/api/v1/repos/tim/app/jobs/7/log",
358 },
359 {
360 Name: "build", Stage: "build", Status: "success", Duration: 8,
361 WebURL: "https://git.example/tim/app/-/pipelines/26/jobs/8",
362 Log: "built bluegit",
363 },
364 },
365 },
366 {
367 Type: EventPush, Project: "tim/app", Actor: "tim", Branch: "master",
368 Ref: "refs/heads/master", Before: strings.Repeat("0", 40), After: "abc123",
369 Commits: []CommitInfo{{
370 SHA: "abc123", Message: "fix de build", Author: "Tim <tim@example.com>",
371 Timestamp: "2026-10-22T12:00:00Z",
372 URL: "https://git.example/tim/app/-/commit/abc123",
373 DiffURL: "https://git.example/api/v1/repos/tim/app/commits/abc123/diff",
374 Files: []FileChange{{
375 Path: "README.md", Status: "modified", Additions: 1, Deletions: 1,
376 }},
377 }},
378 },
379 {
380 Type: EventMergeRequest, Project: "tim/app", Actor: "ada",
381 MergeRequest: &MRInfo{
382 ID: 4, Title: "Toon de kloon-URL", Description: "SSH en HTTPS.",
383 SourceBranch: "feature", TargetBranch: "master", Status: "open",
384 Author: "ada", Action: "opened",
385 URL: "https://git.example/tim/app/-/merge-requests/4",
386 DiffURL: "https://git.example/api/v1/repos/tim/app/merge-requests/4/diff",
387 Reviewers: []ReviewerInfo{{Username: "tim", Status: "approved"}},
388 Comments: []CommentInfo{},
389 Commits: []CommitInfo{{
390 SHA: "abc123", Message: "fix de build", Author: "Tim <tim@example.com>",
391 Timestamp: "2026-10-22T12:00:00Z",
392 URL: "https://git.example/tim/app/-/commit/abc123",
393 DiffURL: "https://git.example/api/v1/repos/tim/app/commits/abc123/diff",
394 Files: []FileChange{{Path: "README.md", Status: "modified", Additions: 1, Deletions: 1}},
395 }},
396 DiffStats: DiffStats{
397 Additions: 1, Deletions: 1,
398 Files: []FileChange{{Path: "README.md", Status: "modified", Additions: 1, Deletions: 1}},
399 },
400 },
401 },
402 {
403 Type: EventRelease, Project: "tim/app", ReleaseTag: "v1.2.0", Commit: "abc123",
404 Release: &ReleaseInfo{
405 Tag: "v1.2.0", Name: "BlueGit 1.2.0", Commit: "abc123",
406 Assets: []AssetInfo{{
407 Name: "bluegit", Size: 8123456,
408 URL: "https://git.example/tim/app/-/releases/v1.2.0/assets/bluegit",
409 }},
410 },
411 },
412 }
413 var b strings.Builder
414 for i, ev := range samples {
415 if i > 0 {
416 b.WriteString("\n\n")
417 }
418 raw, err := json.MarshalIndent(ev.Document(), "", " ")
419 if err != nil {
420 continue
421 }
422 b.Write(raw)
423 }
424 return b.String()
425}
426
427// IssueExample is het voorbeeld van een issue-event op de infopagina.
428func IssueExample() string {
429 ev := Event{
430 Type: EventIssue, Project: "tim/app", Actor: "ada",
431 Summary: "issue #12 opened: Inloggen faalt",
432 URL: "https://git.example/tim/app/-/issues/12",
433 Issue: &IssueInfo{
434 ID: 12, Title: "Inloggen faalt", Description: "Zie #3 en !4.",
435 Status: "open", Confidential: false, Author: "ada",
436 Assignees: []string{"tim"}, Labels: []string{"bug"},
437 Milestone: "v1", DueDate: "2026-11-01", Action: "opened",
438 URL: "https://git.example/tim/app/-/issues/12",
439 },
440 }
441 raw, err := json.MarshalIndent(ev.Document(), "", " ")
442 if err != nil {
443 return ""
444 }
445 return string(raw)
446}
447
448func firstNonEmpty(a, b string) string {
449 if a != "" {
450 return a
451 }
452 return b
453}