BlueGit

timfa bluegit

Files

bluegit / internal / server / hook_payload.go

hook_payload.go

fix: stuur de console-output van elke job mee in pipeline-webhooks
timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa · 3 weeks ago
6080426e History
hook_payload.go 6.7 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 }
25 return ev
26}
27
28func (s *Server) fillPipelineEvent(ctx context.Context, repo store.Repo, ev *webhook.Event) {
29 id, err := strconv.ParseInt(ev.PipelineID, 10, 64)
30 if err != nil || id <= 0 || s.Store == nil {
31 return
32 }
33 p, err := s.Store.PipelineByID(ctx, repo.ID, id)
34 if err != nil {
35 return
36 }
37 base := strings.TrimRight(s.Cfg.BaseURL, "/")
38 pipeURL := base + "/" + repo.FullPath() + "/-/pipelines/" + strconv.FormatInt(p.ID, 10)
39 if ev.URL == "" || !strings.HasPrefix(ev.URL, "http") {
40 ev.URL = pipeURL
41 }
42 if ev.Commit == "" {
43 ev.Commit = p.CommitSHA
44 }
45 if ev.Branch == "" {
46 ev.Branch = refName(p.Ref)
47 }
48 if ev.Actor == "" {
49 ev.Actor = p.Actor
50 }
51 msg := p.CommitTitle
52 author := p.Actor
53 if s.Git != "" && s.StoragePath() != "" && p.CommitSHA != "" {
54 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
55 if c, err := gitrepo.Show(ctx, s.Git, dir, p.CommitSHA); err == nil && c.SHA != "" {
56 if text := commitText(c); text != "" {
57 msg = text
58 }
59 if author == "" {
60 author = commitAuthor(c)
61 }
62 }
63 }
64 ev.PipelineID = strconv.FormatInt(p.ID, 10)
65 ev.Pipeline = &webhook.PipelineInfo{
66 ID: p.ID, Status: p.Status, Ref: p.Ref, SHA: p.CommitSHA,
67 CommitMessage: msg, Author: author, Duration: elapsedSeconds(p.StartedAt, p.FinishedAt),
68 URL: pipeURL,
69 }
70 jobs, err := s.Store.JobsByPipeline(ctx, p.ID)
71 if err != nil {
72 return
73 }
74 secrets := s.maskSecrets(ctx, repo)
75 ev.Jobs = make([]webhook.JobInfo, 0, len(jobs))
76 for _, j := range jobs {
77 logText, truncated := webhook.TailLog(j.Log, secrets)
78 info := webhook.JobInfo{
79 Name: j.Name, Stage: j.Stage, Status: j.Status,
80 Duration: elapsedSeconds(j.StartedAt, j.FinishedAt),
81 AllowFailure: j.AllowFailure,
82 WebURL: pipeURL + "/jobs/" + strconv.FormatInt(j.ID, 10),
83 Log: logText,
84 LogTruncated: truncated,
85 }
86 if truncated {
87 info.LogURL = jobLogAPIURL(s.Cfg.BaseURL, repo, j.ID)
88 }
89 ev.Jobs = append(ev.Jobs, info)
90 }
91}
92
93func (s *Server) fillPushEvent(ctx context.Context, repo store.Repo, ev *webhook.Event) {
94 if ev.Commits != nil || s.Git == "" || s.StoragePath() == "" || ev.After == "" {
95 if ev.Commits == nil {
96 ev.Commits = []webhook.CommitInfo{}
97 }
98 return
99 }
100 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
101 list, err := gitrepo.RangeLog(ctx, s.Git, dir, ev.Before, ev.After)
102 if err != nil || len(list) == 0 {
103 ev.Commits = []webhook.CommitInfo{}
104 return
105 }
106 if len(list) > webhook.MaxPushCommits {
107 list = list[:webhook.MaxPushCommits]
108 }
109 base := strings.TrimRight(s.Cfg.BaseURL, "/")
110 ev.Commits = make([]webhook.CommitInfo, 0, len(list))
111 for i := len(list) - 1; i >= 0; i-- {
112 c := list[i]
113 ev.Commits = append(ev.Commits, webhook.CommitInfo{
114 SHA: c.SHA, Message: commitText(c), Author: commitAuthor(c),
115 URL: base + "/" + repo.FullPath() + "/-/commit/" + c.SHA,
116 })
117 }
118}
119
120func (s *Server) maskSecrets(ctx context.Context, repo store.Repo) []string {
121 if s.Store == nil {
122 return nil
123 }
124 var out []string
125 add := func(kind string, id int64) {
126 vals, err := s.Store.SecretValues(ctx, kind, id, true)
127 if err != nil {
128 return
129 }
130 for _, v := range vals {
131 out = append(out, v)
132 }
133 }
134 add("repo", repo.ID)
135 if repo.OwnerKind == "group" {
136 add("group", repo.OwnerID)
137 }
138 return out
139}
140
141func (s *Server) mrEvent(repo store.Repo, mr store.MergeRequest, actor, action, comment string) webhook.Event {
142 num := strconv.FormatInt(mr.Number, 10)
143 path := strings.TrimRight(s.Cfg.BaseURL, "/") + repoURL(repo) + "/-/merge-requests/" + num
144 summary := i18n.T(i18n.EN, "hook.mr", num, mr.Title)
145 switch action {
146 case "merged":
147 summary = i18n.T(i18n.EN, "hook.mrMerged", num, mr.Title)
148 case "commented":
149 summary = i18n.T(i18n.EN, "hook.mrComment", num)
150 }
151 return webhook.Event{
152 Type: webhook.EventMergeRequest,
153 Project: repo.FullPath(),
154 Branch: mr.TargetBranch,
155 Actor: actor,
156 Summary: summary,
157 URL: path,
158 Comment: comment,
159 MergeRequest: &webhook.MRInfo{
160 ID: mr.Number, Title: mr.Title, Description: mr.Description,
161 SourceBranch: mr.SourceBranch, TargetBranch: mr.TargetBranch,
162 Status: mr.Status, Author: mr.Author, Action: action, URL: path,
163 },
164 }
165}
166
167func (s *Server) mrHook(repo store.Repo, mr store.MergeRequest, actor, action, comment string) {
168 s.Dispatch(repo.ID, s.mrEvent(repo, mr, actor, action, comment))
169}
170
171func (s *Server) releaseEvent(repo store.Repo, tag, name, commit string, assets []store.ReleaseAsset) webhook.Event {
172 base := strings.TrimRight(s.Cfg.BaseURL, "/")
173 page := base + repoURL(repo) + "/-/releases"
174 list := make([]webhook.AssetInfo, 0, len(assets))
175 for _, a := range assets {
176 list = append(list, webhook.AssetInfo{
177 Name: a.Name, Size: a.Size,
178 URL: base + repoURL(repo) + "/-/releases/" + url.PathEscape(tag) + "/assets/" + url.PathEscape(a.Name),
179 })
180 }
181 return webhook.Event{
182 Type: webhook.EventRelease, Project: repo.FullPath(), Commit: commit,
183 ReleaseTag: tag, Summary: i18n.T(i18n.EN, "hook.release", tag, repo.FullPath()),
184 URL: page,
185 Release: &webhook.ReleaseInfo{Tag: tag, Name: name, Commit: commit, Assets: list},
186 }
187}
188
189func jobLogAPIURL(base string, repo store.Repo, jobID int64) string {
190 return strings.TrimRight(base, "/") + "/api/v1/repos/" + url.PathEscape(repo.OwnerPath) + "/" + url.PathEscape(repo.Name) + "/jobs/" + strconv.FormatInt(jobID, 10) + "/log"
191}
192
193func refName(ref string) string {
194 if b, ok := gitrepo.BranchOfRef(ref); ok {
195 return b
196 }
197 if name, ok := strings.CutPrefix(ref, "refs/tags/"); ok && name != "" {
198 return name
199 }
200 return ref
201}
202
203func commitText(c gitrepo.Commit) string {
204 if c.Subject == "" {
205 return strings.TrimSpace(c.Body)
206 }
207 if strings.TrimSpace(c.Body) == "" {
208 return c.Subject
209 }
210 return c.Subject + "\n\n" + strings.TrimSpace(c.Body)
211}
212
213func commitAuthor(c gitrepo.Commit) string {
214 name := strings.TrimSpace(c.Author)
215 email := strings.TrimSpace(c.Email)
216 switch {
217 case name == "":
218 return email
219 case email == "":
220 return name
221 default:
222 return name + " <" + email + ">"
223 }
224}
225
226func elapsedSeconds(start, end time.Time) float64 {
227 if start.IsZero() || end.IsZero() || end.Before(start) {
228 return 0
229 }
230 return math.Round(end.Sub(start).Seconds()*1000) / 1000
231}