BlueGit

timfa bluegit

Files

bluegit / internal / server / hook_payload.go

hook_payload.go

fix: noem de diff-lezer CommitFileChanges
timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa · 3 weeks ago
6ef4ea8e History
hook_payload.go 10.2 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 }
88 if truncated {
89 info.LogURL = jobLogAPIURL(s.Cfg.BaseURL, repo, j.ID)
90 }
91 ev.Jobs = append(ev.Jobs, info)
92 }
93}
94
95func (s *Server) fillPushEvent(ctx context.Context, repo store.Repo, ev *webhook.Event) {
96 if ev.Commits != nil || s.Git == "" || s.StoragePath() == "" || ev.After == "" {
97 if ev.Commits == nil {
98 ev.Commits = []webhook.CommitInfo{}
99 }
100 return
101 }
102 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
103 list, err := gitrepo.RangeLog(ctx, s.Git, dir, ev.Before, ev.After)
104 if err != nil || len(list) == 0 {
105 ev.Commits = []webhook.CommitInfo{}
106 return
107 }
108 if len(list) > webhook.MaxPushCommits {
109 list = list[:webhook.MaxPushCommits]
110 }
111 ev.Commits = make([]webhook.CommitInfo, 0, len(list))
112 for i := len(list) - 1; i >= 0; i-- {
113 ev.Commits = append(ev.Commits, s.commitInfo(ctx, repo, list[i]))
114 }
115}
116
117func (s *Server) fillMREvent(ctx context.Context, repo store.Repo, ev *webhook.Event) {
118 if ev.MergeRequest == nil {
119 return
120 }
121 mr := ev.MergeRequest
122 if mr.Reviewers == nil {
123 mr.Reviewers = []webhook.ReviewerInfo{}
124 }
125 if mr.Comments == nil {
126 mr.Comments = []webhook.CommentInfo{}
127 }
128 if mr.Commits == nil {
129 mr.Commits = []webhook.CommitInfo{}
130 }
131 if mr.DiffStats.Files == nil {
132 mr.DiffStats.Files = []webhook.FileChange{}
133 }
134 mr.DiffURL = mrDiffAPIURL(s.Cfg.BaseURL, repo, mr.ID)
135 if s.Store != nil && mr.ID > 0 {
136 if stored, err := s.Store.MergeRequestByNumber(ctx, repo.ID, mr.ID); err == nil {
137 if revs, err := s.Store.ListReviews(ctx, stored.ID); err == nil {
138 mr.Reviewers = make([]webhook.ReviewerInfo, 0, len(revs))
139 for _, rev := range revs {
140 mr.Reviewers = append(mr.Reviewers, webhook.ReviewerInfo{Username: rev.Username, Status: rev.Status})
141 }
142 }
143 if notes, err := s.Store.ListNotes(ctx, stored.ID); err == nil {
144 mr.Comments = make([]webhook.CommentInfo, 0, len(notes))
145 for _, n := range notes {
146 mr.Comments = append(mr.Comments, webhook.CommentInfo{
147 ID: n.ID, Author: n.Author, Body: n.Body,
148 CreatedAt: n.CreatedAt.UTC().Format(time.RFC3339),
149 FilePath: n.FilePath, LineStart: n.LineStart, LineEnd: n.LineEnd,
150 ParentID: n.ParentID,
151 })
152 }
153 }
154 }
155 }
156 if s.Git == "" || s.StoragePath() == "" || mr.SourceBranch == "" || mr.TargetBranch == "" {
157 return
158 }
159 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
160 if changes, err := gitrepo.CompareChanges(ctx, s.Git, dir, mr.TargetBranch, mr.SourceBranch); err == nil {
161 stats := webhook.DiffStats{Files: fileChanges(changes)}
162 for _, f := range stats.Files {
163 stats.Additions += f.Additions
164 stats.Deletions += f.Deletions
165 }
166 mr.DiffStats = stats
167 }
168 list, err := gitrepo.Log(ctx, s.Git, dir, mr.TargetBranch+".."+mr.SourceBranch, webhook.MaxPushCommits)
169 if err != nil || len(list) == 0 {
170 mr.Commits = []webhook.CommitInfo{}
171 return
172 }
173 mr.Commits = make([]webhook.CommitInfo, 0, len(list))
174 for i := len(list) - 1; i >= 0; i-- {
175 mr.Commits = append(mr.Commits, s.commitInfo(ctx, repo, list[i]))
176 }
177}
178
179func (s *Server) commitInfo(ctx context.Context, repo store.Repo, c gitrepo.Commit) webhook.CommitInfo {
180 base := strings.TrimRight(s.Cfg.BaseURL, "/")
181 info := webhook.CommitInfo{
182 SHA: c.SHA, Message: commitText(c), Author: commitAuthor(c),
183 Timestamp: time.Unix(c.Unix, 0).UTC().Format(time.RFC3339),
184 URL: base + "/" + repo.FullPath() + "/-/commit/" + c.SHA,
185 DiffURL: commitDiffAPIURL(base, repo, c.SHA),
186 Files: []webhook.FileChange{},
187 }
188 if s.Git == "" || s.StoragePath() == "" {
189 return info
190 }
191 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
192 files, err := gitrepo.CommitFileChanges(ctx, s.Git, dir, c.SHA)
193 if err != nil {
194 return info
195 }
196 info.Files = fileChanges(files)
197 return info
198}
199
200func fileChanges(list []gitrepo.Change) []webhook.FileChange {
201 out := make([]webhook.FileChange, 0, len(list))
202 for _, c := range list {
203 out = append(out, webhook.FileChange{
204 Path: c.Path, Status: c.Status, PreviousPath: c.OldPath,
205 Additions: c.Added, Deletions: c.Deleted, Binary: c.Binary,
206 })
207 }
208 return out
209}
210
211func (s *Server) maskSecrets(ctx context.Context, repo store.Repo) []string {
212 if s.Store == nil {
213 return nil
214 }
215 var out []string
216 add := func(kind string, id int64) {
217 vals, err := s.Store.SecretValues(ctx, kind, id, true)
218 if err != nil {
219 return
220 }
221 for _, v := range vals {
222 out = append(out, v)
223 }
224 }
225 add("repo", repo.ID)
226 if repo.OwnerKind == "group" {
227 add("group", repo.OwnerID)
228 }
229 return out
230}
231
232func (s *Server) mrEvent(repo store.Repo, mr store.MergeRequest, actor, action, comment string) webhook.Event {
233 num := strconv.FormatInt(mr.Number, 10)
234 path := strings.TrimRight(s.Cfg.BaseURL, "/") + repoURL(repo) + "/-/merge-requests/" + num
235 summary := i18n.T(i18n.EN, "hook.mr", num, mr.Title)
236 switch action {
237 case "merged":
238 summary = i18n.T(i18n.EN, "hook.mrMerged", num, mr.Title)
239 case "commented":
240 summary = i18n.T(i18n.EN, "hook.mrComment", num)
241 }
242 return webhook.Event{
243 Type: webhook.EventMergeRequest,
244 Project: repo.FullPath(),
245 Branch: mr.TargetBranch,
246 Actor: actor,
247 Summary: summary,
248 URL: path,
249 Comment: comment,
250 MergeRequest: &webhook.MRInfo{
251 ID: mr.Number, Title: mr.Title, Description: mr.Description,
252 SourceBranch: mr.SourceBranch, TargetBranch: mr.TargetBranch,
253 Status: mr.Status, Author: mr.Author, Action: action, URL: path,
254 },
255 }
256}
257
258func (s *Server) mrHook(repo store.Repo, mr store.MergeRequest, actor, action, comment string) {
259 s.Dispatch(repo.ID, s.mrEvent(repo, mr, actor, action, comment))
260}
261
262func (s *Server) releaseEvent(repo store.Repo, tag, name, commit string, assets []store.ReleaseAsset) webhook.Event {
263 base := strings.TrimRight(s.Cfg.BaseURL, "/")
264 page := base + repoURL(repo) + "/-/releases"
265 list := make([]webhook.AssetInfo, 0, len(assets))
266 for _, a := range assets {
267 list = append(list, webhook.AssetInfo{
268 Name: a.Name, Size: a.Size,
269 URL: base + repoURL(repo) + "/-/releases/" + url.PathEscape(tag) + "/assets/" + url.PathEscape(a.Name),
270 })
271 }
272 return webhook.Event{
273 Type: webhook.EventRelease, Project: repo.FullPath(), Commit: commit,
274 ReleaseTag: tag, Summary: i18n.T(i18n.EN, "hook.release", tag, repo.FullPath()),
275 URL: page,
276 Release: &webhook.ReleaseInfo{Tag: tag, Name: name, Commit: commit, Assets: list},
277 }
278}
279
280func commitDiffAPIURL(base string, repo store.Repo, sha string) string {
281 return strings.TrimRight(base, "/") + "/api/v1/repos/" + url.PathEscape(repo.OwnerPath) + "/" + url.PathEscape(repo.Name) + "/commits/" + url.PathEscape(sha) + "/diff"
282}
283
284func mrDiffAPIURL(base string, repo store.Repo, number int64) string {
285 return strings.TrimRight(base, "/") + "/api/v1/repos/" + url.PathEscape(repo.OwnerPath) + "/" + url.PathEscape(repo.Name) + "/merge-requests/" + strconv.FormatInt(number, 10) + "/diff"
286}
287
288func jobLogAPIURL(base string, repo store.Repo, jobID int64) string {
289 return strings.TrimRight(base, "/") + "/api/v1/repos/" + url.PathEscape(repo.OwnerPath) + "/" + url.PathEscape(repo.Name) + "/jobs/" + strconv.FormatInt(jobID, 10) + "/log"
290}
291
292func refName(ref string) string {
293 if b, ok := gitrepo.BranchOfRef(ref); ok {
294 return b
295 }
296 if name, ok := strings.CutPrefix(ref, "refs/tags/"); ok && name != "" {
297 return name
298 }
299 return ref
300}
301
302func commitText(c gitrepo.Commit) string {
303 if c.Subject == "" {
304 return strings.TrimSpace(c.Body)
305 }
306 if strings.TrimSpace(c.Body) == "" {
307 return c.Subject
308 }
309 return c.Subject + "\n\n" + strings.TrimSpace(c.Body)
310}
311
312func commitAuthor(c gitrepo.Commit) string {
313 name := strings.TrimSpace(c.Author)
314 email := strings.TrimSpace(c.Email)
315 switch {
316 case name == "":
317 return email
318 case email == "":
319 return name
320 default:
321 return name + " <" + email + ">"
322 }
323}
324
325func elapsedSeconds(start, end time.Time) float64 {
326 if start.IsZero() || end.IsZero() || end.Before(start) {
327 return 0
328 }
329 return math.Round(end.Sub(start).Seconds()*1000) / 1000
330}