BlueGit

timfa bluegit

Files

bluegit / internal / server / hook_payload.go

hook_payload.go

hook_payload.go 10.3 KiB Download Raw
1package server
2
3import (
4 "context"
5 "math"
6 "net/url"
7 "strconv"
8 "strings"
9 "time"
10
11 "gitlab.com/Timfa/bluegit/internal/gitrepo"
12 "gitlab.com/Timfa/bluegit/internal/i18n"
13 "gitlab.com/Timfa/bluegit/internal/store"
14 "gitlab.com/Timfa/bluegit/internal/webhook"
15)
16
17// enrichEvent vult de details die de JSON-body van een webhook meestuurt.
18func (s *Server) enrichEvent(ctx context.Context, repo store.Repo, ev webhook.Event) webhook.Event {
19 switch ev.Type {
20 case webhook.EventPipelineSuccess, webhook.EventPipelineFailure:
21 s.fillPipelineEvent(ctx, repo, &ev)
22 case webhook.EventPush:
23 s.fillPushEvent(ctx, repo, &ev)
24 case webhook.EventMergeRequest:
25 s.fillMREvent(ctx, repo, &ev)
26 }
27 return ev
28}
29
30func (s *Server) fillPipelineEvent(ctx context.Context, repo store.Repo, ev *webhook.Event) {
31 id, err := strconv.ParseInt(ev.PipelineID, 10, 64)
32 if err != nil || id <= 0 || s.Store == nil {
33 return
34 }
35 p, err := s.Store.PipelineByID(ctx, repo.ID, id)
36 if err != nil {
37 return
38 }
39 base := strings.TrimRight(s.Cfg.BaseURL, "/")
40 pipeURL := base + "/" + repo.FullPath() + "/-/pipelines/" + strconv.FormatInt(p.ID, 10)
41 if ev.URL == "" || !strings.HasPrefix(ev.URL, "http") {
42 ev.URL = pipeURL
43 }
44 if ev.Commit == "" {
45 ev.Commit = p.CommitSHA
46 }
47 if ev.Branch == "" {
48 ev.Branch = refName(p.Ref)
49 }
50 if ev.Actor == "" {
51 ev.Actor = p.Actor
52 }
53 msg := p.CommitTitle
54 author := p.Actor
55 if s.Git != "" && s.StoragePath() != "" && p.CommitSHA != "" {
56 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
57 if c, err := gitrepo.Show(ctx, s.Git, dir, p.CommitSHA); err == nil && c.SHA != "" {
58 if text := commitText(c); text != "" {
59 msg = text
60 }
61 if author == "" {
62 author = commitAuthor(c)
63 }
64 }
65 }
66 ev.PipelineID = strconv.FormatInt(p.ID, 10)
67 ev.Pipeline = &webhook.PipelineInfo{
68 ID: p.ID, Status: p.Status, Ref: p.Ref, SHA: p.CommitSHA,
69 CommitMessage: msg, Author: author, Duration: elapsedSeconds(p.StartedAt, p.FinishedAt),
70 URL: pipeURL,
71 }
72 jobs, err := s.Store.JobsByPipeline(ctx, p.ID)
73 if err != nil {
74 return
75 }
76 secrets := s.maskSecrets(ctx, repo)
77 ev.Jobs = make([]webhook.JobInfo, 0, len(jobs))
78 for _, j := range jobs {
79 logText, truncated := webhook.TailLog(j.Log, secrets)
80 info := webhook.JobInfo{
81 Name: j.Name, Stage: j.Stage, Status: j.Status,
82 Duration: elapsedSeconds(j.StartedAt, j.FinishedAt),
83 AllowFailure: j.AllowFailure,
84 WebURL: pipeURL + "/jobs/" + strconv.FormatInt(j.ID, 10),
85 Log: logText,
86 LogTruncated: truncated,
87 CancelReason: j.CancelReason(), FailureReason: j.FailureReason(),
88 }
89 if truncated {
90 info.LogURL = jobLogAPIURL(s.Cfg.BaseURL, repo, j.ID)
91 }
92 ev.Jobs = append(ev.Jobs, info)
93 }
94}
95
96func (s *Server) fillPushEvent(ctx context.Context, repo store.Repo, ev *webhook.Event) {
97 if ev.Commits != nil || s.Git == "" || s.StoragePath() == "" || ev.After == "" {
98 if ev.Commits == nil {
99 ev.Commits = []webhook.CommitInfo{}
100 }
101 return
102 }
103 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
104 list, err := gitrepo.RangeLog(ctx, s.Git, dir, ev.Before, ev.After)
105 if err != nil || len(list) == 0 {
106 ev.Commits = []webhook.CommitInfo{}
107 return
108 }
109 if len(list) > webhook.MaxPushCommits {
110 list = list[:webhook.MaxPushCommits]
111 }
112 ev.Commits = make([]webhook.CommitInfo, 0, len(list))
113 for i := len(list) - 1; i >= 0; i-- {
114 ev.Commits = append(ev.Commits, s.commitInfo(ctx, repo, list[i]))
115 }
116}
117
118func (s *Server) fillMREvent(ctx context.Context, repo store.Repo, ev *webhook.Event) {
119 if ev.MergeRequest == nil {
120 return
121 }
122 mr := ev.MergeRequest
123 if mr.Reviewers == nil {
124 mr.Reviewers = []webhook.ReviewerInfo{}
125 }
126 if mr.Comments == nil {
127 mr.Comments = []webhook.CommentInfo{}
128 }
129 if mr.Commits == nil {
130 mr.Commits = []webhook.CommitInfo{}
131 }
132 if mr.DiffStats.Files == nil {
133 mr.DiffStats.Files = []webhook.FileChange{}
134 }
135 mr.DiffURL = mrDiffAPIURL(s.Cfg.BaseURL, repo, mr.ID)
136 if s.Store != nil && mr.ID > 0 {
137 if stored, err := s.Store.MergeRequestByNumber(ctx, repo.ID, mr.ID); err == nil {
138 if revs, err := s.Store.ListReviews(ctx, stored.ID); err == nil {
139 mr.Reviewers = make([]webhook.ReviewerInfo, 0, len(revs))
140 for _, rev := range revs {
141 mr.Reviewers = append(mr.Reviewers, webhook.ReviewerInfo{Username: rev.Username, Status: rev.Status})
142 }
143 }
144 if notes, err := s.Store.ListNotes(ctx, stored.ID); err == nil {
145 mr.Comments = make([]webhook.CommentInfo, 0, len(notes))
146 for _, n := range notes {
147 mr.Comments = append(mr.Comments, webhook.CommentInfo{
148 ID: n.ID, Author: n.Author, Body: n.Body,
149 CreatedAt: n.CreatedAt.UTC().Format(time.RFC3339),
150 FilePath: n.FilePath, LineStart: n.LineStart, LineEnd: n.LineEnd,
151 ParentID: n.ParentID,
152 })
153 }
154 }
155 }
156 }
157 if s.Git == "" || s.StoragePath() == "" || mr.SourceBranch == "" || mr.TargetBranch == "" {
158 return
159 }
160 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
161 if changes, err := gitrepo.CompareChanges(ctx, s.Git, dir, mr.TargetBranch, mr.SourceBranch); err == nil {
162 stats := webhook.DiffStats{Files: fileChanges(changes)}
163 for _, f := range stats.Files {
164 stats.Additions += f.Additions
165 stats.Deletions += f.Deletions
166 }
167 mr.DiffStats = stats
168 }
169 list, err := gitrepo.Log(ctx, s.Git, dir, mr.TargetBranch+".."+mr.SourceBranch, webhook.MaxPushCommits)
170 if err != nil || len(list) == 0 {
171 mr.Commits = []webhook.CommitInfo{}
172 return
173 }
174 mr.Commits = make([]webhook.CommitInfo, 0, len(list))
175 for i := len(list) - 1; i >= 0; i-- {
176 mr.Commits = append(mr.Commits, s.commitInfo(ctx, repo, list[i]))
177 }
178}
179
180func (s *Server) commitInfo(ctx context.Context, repo store.Repo, c gitrepo.Commit) webhook.CommitInfo {
181 base := strings.TrimRight(s.Cfg.BaseURL, "/")
182 info := webhook.CommitInfo{
183 SHA: c.SHA, Message: commitText(c), Author: commitAuthor(c),
184 Timestamp: time.Unix(c.Unix, 0).UTC().Format(time.RFC3339),
185 URL: base + "/" + repo.FullPath() + "/-/commit/" + c.SHA,
186 DiffURL: commitDiffAPIURL(base, repo, c.SHA),
187 Files: []webhook.FileChange{},
188 }
189 if s.Git == "" || s.StoragePath() == "" {
190 return info
191 }
192 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
193 files, err := gitrepo.CommitFileChanges(ctx, s.Git, dir, c.SHA)
194 if err != nil {
195 return info
196 }
197 info.Files = fileChanges(files)
198 return info
199}
200
201func fileChanges(list []gitrepo.Change) []webhook.FileChange {
202 out := make([]webhook.FileChange, 0, len(list))
203 for _, c := range list {
204 out = append(out, webhook.FileChange{
205 Path: c.Path, Status: c.Status, PreviousPath: c.OldPath,
206 Additions: c.Added, Deletions: c.Deleted, Binary: c.Binary,
207 })
208 }
209 return out
210}
211
212func (s *Server) maskSecrets(ctx context.Context, repo store.Repo) []string {
213 if s.Store == nil {
214 return nil
215 }
216 var out []string
217 add := func(kind string, id int64) {
218 vals, err := s.Store.SecretValues(ctx, kind, id, true)
219 if err != nil {
220 return
221 }
222 for _, v := range vals {
223 out = append(out, v)
224 }
225 }
226 add("repo", repo.ID)
227 if repo.OwnerKind == "group" {
228 add("group", repo.OwnerID)
229 }
230 return out
231}
232
233func (s *Server) mrEvent(repo store.Repo, mr store.MergeRequest, actor, action, comment string) webhook.Event {
234 num := strconv.FormatInt(mr.Number, 10)
235 path := strings.TrimRight(s.Cfg.BaseURL, "/") + repoURL(repo) + "/-/merge-requests/" + num
236 summary := i18n.T(i18n.EN, "hook.mr", num, mr.Title)
237 switch action {
238 case "merged":
239 summary = i18n.T(i18n.EN, "hook.mrMerged", num, mr.Title)
240 case "commented":
241 summary = i18n.T(i18n.EN, "hook.mrComment", num)
242 }
243 return webhook.Event{
244 Type: webhook.EventMergeRequest,
245 Project: repo.FullPath(),
246 Branch: mr.TargetBranch,
247 Actor: actor,
248 Summary: summary,
249 URL: path,
250 Comment: comment,
251 MergeRequest: &webhook.MRInfo{
252 ID: mr.Number, Title: mr.Title, Description: mr.Description,
253 SourceBranch: mr.SourceBranch, TargetBranch: mr.TargetBranch,
254 Status: mr.Status, Author: mr.Author, Action: action, URL: path,
255 },
256 }
257}
258
259func (s *Server) mrHook(repo store.Repo, mr store.MergeRequest, actor, action, comment string) {
260 s.Dispatch(repo.ID, s.mrEvent(repo, mr, actor, action, comment))
261}
262
263func (s *Server) releaseEvent(repo store.Repo, tag, name, commit string, assets []store.ReleaseAsset) webhook.Event {
264 base := strings.TrimRight(s.Cfg.BaseURL, "/")
265 page := base + repoURL(repo) + "/-/releases"
266 list := make([]webhook.AssetInfo, 0, len(assets))
267 for _, a := range assets {
268 list = append(list, webhook.AssetInfo{
269 Name: a.Name, Size: a.Size,
270 URL: base + repoURL(repo) + "/-/releases/" + url.PathEscape(tag) + "/assets/" + url.PathEscape(a.Name),
271 })
272 }
273 return webhook.Event{
274 Type: webhook.EventRelease, Project: repo.FullPath(), Commit: commit,
275 ReleaseTag: tag, Summary: i18n.T(i18n.EN, "hook.release", tag, repo.FullPath()),
276 URL: page,
277 Release: &webhook.ReleaseInfo{Tag: tag, Name: name, Commit: commit, Assets: list},
278 }
279}
280
281func commitDiffAPIURL(base string, repo store.Repo, sha string) string {
282 return strings.TrimRight(base, "/") + "/api/v1/repos/" + url.PathEscape(repo.OwnerPath) + "/" + url.PathEscape(repo.Name) + "/commits/" + url.PathEscape(sha) + "/diff"
283}
284
285func mrDiffAPIURL(base string, repo store.Repo, number int64) string {
286 return strings.TrimRight(base, "/") + "/api/v1/repos/" + url.PathEscape(repo.OwnerPath) + "/" + url.PathEscape(repo.Name) + "/merge-requests/" + strconv.FormatInt(number, 10) + "/diff"
287}
288
289func jobLogAPIURL(base string, repo store.Repo, jobID int64) string {
290 return strings.TrimRight(base, "/") + "/api/v1/repos/" + url.PathEscape(repo.OwnerPath) + "/" + url.PathEscape(repo.Name) + "/jobs/" + strconv.FormatInt(jobID, 10) + "/log"
291}
292
293func refName(ref string) string {
294 if b, ok := gitrepo.BranchOfRef(ref); ok {
295 return b
296 }
297 if name, ok := strings.CutPrefix(ref, "refs/tags/"); ok && name != "" {
298 return name
299 }
300 return ref
301}
302
303func commitText(c gitrepo.Commit) string {
304 if c.Subject == "" {
305 return strings.TrimSpace(c.Body)
306 }
307 if strings.TrimSpace(c.Body) == "" {
308 return c.Subject
309 }
310 return c.Subject + "\n\n" + strings.TrimSpace(c.Body)
311}
312
313func commitAuthor(c gitrepo.Commit) string {
314 name := strings.TrimSpace(c.Author)
315 email := strings.TrimSpace(c.Email)
316 switch {
317 case name == "":
318 return email
319 case email == "":
320 return name
321 default:
322 return name + " <" + email + ">"
323 }
324}
325
326func elapsedSeconds(start, end time.Time) float64 {
327 if start.IsZero() || end.IsZero() || end.Before(start) {
328 return 0
329 }
330 return math.Round(end.Sub(start).Seconds()*1000) / 1000
331}