BlueGit

timfa bluegit

Files

bluegit / internal / webhook / payload.go

payload.go

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