BlueGit

timfa bluegit

Files

bluegit / internal / webhook / payload.go

payload.go

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