BlueGit

timfa bluegit

Files

bluegit / internal / webhook / payload.go

payload.go

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