BlueGit

timfa bluegit

Files

bluegit / internal / server / api_flow.go

api_flow.go

api_flow.go 23.2 KiB Download Raw
1package server
2
3import (
4 "context"
5 "net/http"
6 "strconv"
7 "strings"
8
9 "gitlab.com/Timfa/bluegit/internal/access"
10 "gitlab.com/Timfa/bluegit/internal/i18n"
11 "gitlab.com/Timfa/bluegit/internal/images"
12 "gitlab.com/Timfa/bluegit/internal/store"
13)
14
15func (s *Server) pageURL(repo store.Repo, suffix string) string {
16 if !strings.HasPrefix(suffix, "/") {
17 suffix = "/" + suffix
18 }
19 return strings.TrimRight(s.Cfg.BaseURL, "/") + "/" + repo.FullPath() + suffix
20}
21
22func (s *Server) mrJSON(repo store.Repo, mr store.MergeRequest) map[string]any {
23 return map[string]any{
24 "id": mr.ID, "iid": mr.Number, "title": mr.Title, "description": mr.Description,
25 "source_branch": mr.SourceBranch, "target_branch": mr.TargetBranch,
26 "author": mr.Author, "state": mr.Status, "draft": mr.Draft, "labels": mr.Labels,
27 "remove_source_branch": mr.RemoveSourceBranch, "squash": mr.Squash,
28 "squash_commit_message": mr.SquashMessage,
29 "web_url": s.pageURL(repo, "/-/merge-requests/"+strconv.FormatInt(mr.Number, 10)),
30 "created_at": rfcTime(mr.CreatedAt), "updated_at": rfcTime(mr.UpdatedAt),
31 }
32}
33
34func (s *Server) apiMRs(w http.ResponseWriter, r *http.Request) {
35 repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
36 if !ok {
37 return
38 }
39 if r.Method == http.MethodPost {
40 var body struct {
41 Title string `json:"title"`
42 Description string `json:"description"`
43 SourceBranch string `json:"source_branch"`
44 TargetBranch string `json:"target_branch"`
45 Draft bool `json:"draft"`
46 Remove *bool `json:"remove_source_branch"`
47 Squash *bool `json:"squash"`
48 Message *string `json:"squash_commit_message"`
49 }
50 if err := readJSON(r, &body); err != nil {
51 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
52 return
53 }
54 mr, err := s.opCreateMR(r.Context(), apiUser(r), repo, body.Title, body.Description, body.SourceBranch, body.TargetBranch, body.Draft)
55 if !s.apiOK(w, r, err) {
56 return
57 }
58 remove, squash, message := true, false, ""
59 if body.Remove != nil {
60 remove = *body.Remove
61 }
62 if body.Squash != nil {
63 squash = *body.Squash
64 }
65 if body.Message != nil {
66 message = *body.Message
67 }
68 if err := s.Store.SetMergeOptions(r.Context(), mr.ID, remove, squash, message); !s.apiOK(w, r, err) {
69 return
70 }
71 mr, err = s.Store.MergeRequestByNumber(r.Context(), repo.ID, mr.Number)
72 if !s.apiOK(w, r, err) {
73 return
74 }
75 writeJSON(w, http.StatusCreated, s.mrJSON(repo, mr))
76 return
77 }
78 list, err := s.Store.ListMergeRequests(r.Context(), repo.ID)
79 if !s.apiOK(w, r, err) {
80 return
81 }
82 // Optionele filters: state (open, merged, closed of all), source_branch, target_branch.
83 q := r.URL.Query()
84 wantState := strings.TrimSpace(q.Get("state"))
85 wantSource := strings.TrimSpace(q.Get("source_branch"))
86 wantTarget := strings.TrimSpace(q.Get("target_branch"))
87 page, per := pageQuery(r)
88 rows := make([]map[string]any, 0, len(list))
89 for _, mr := range list {
90 if wantState != "" && wantState != "all" && mr.Status != wantState {
91 continue
92 }
93 if wantSource != "" && mr.SourceBranch != wantSource {
94 continue
95 }
96 if wantTarget != "" && mr.TargetBranch != wantTarget {
97 continue
98 }
99 rows = append(rows, s.mrJSON(repo, mr))
100 }
101 writePage(w, r, slicePage(rows, page, per), len(rows), page, per)
102}
103
104func (s *Server) apiMR(w http.ResponseWriter, r *http.Request) {
105 repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
106 if !ok {
107 return
108 }
109 n, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
110 if err != nil {
111 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
112 return
113 }
114 if r.Method == http.MethodPut {
115 var body struct {
116 Title string `json:"title"`
117 Description string `json:"description"`
118 Labels string `json:"labels"`
119 Remove *bool `json:"remove_source_branch"`
120 Squash *bool `json:"squash"`
121 Message *string `json:"squash_commit_message"`
122 }
123 if err := readJSON(r, &body); err != nil {
124 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
125 return
126 }
127 mr, err := s.opUpdateMR(r.Context(), apiUser(r), repo, n, body.Title, body.Description, body.Labels)
128 if !s.apiOK(w, r, err) {
129 return
130 }
131 if body.Remove != nil || body.Squash != nil || body.Message != nil {
132 remove, squash, message := mr.RemoveSourceBranch, mr.Squash, mr.SquashMessage
133 if body.Remove != nil {
134 remove = *body.Remove
135 }
136 if body.Squash != nil {
137 squash = *body.Squash
138 }
139 if body.Message != nil {
140 message = *body.Message
141 }
142 if err := s.Store.SetMergeOptions(r.Context(), mr.ID, remove, squash, message); !s.apiOK(w, r, err) {
143 return
144 }
145 mr, err = s.Store.MergeRequestByNumber(r.Context(), repo.ID, mr.Number)
146 if !s.apiOK(w, r, err) {
147 return
148 }
149 }
150 writeJSON(w, http.StatusOK, s.mrJSON(repo, mr))
151 return
152 }
153 mr, err := s.Store.MergeRequestByNumber(r.Context(), repo.ID, n)
154 if err != nil {
155 s.writeAPIErr(w, r, notFound(err))
156 return
157 }
158 writeJSON(w, http.StatusOK, s.mrJSON(repo, mr))
159}
160
161func (s *Server) apiMRNotes(w http.ResponseWriter, r *http.Request) {
162 repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
163 if !ok {
164 return
165 }
166 n, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
167 if err != nil {
168 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
169 return
170 }
171 if r.Method == http.MethodGet {
172 mr, err := s.Store.MergeRequestByNumber(r.Context(), repo.ID, n)
173 if err != nil {
174 s.writeAPIErr(w, r, notFound(err))
175 return
176 }
177 notes, err := s.Store.ListNotes(r.Context(), mr.ID)
178 if !s.apiOK(w, r, err) {
179 return
180 }
181 rows := make([]map[string]any, 0, len(notes))
182 for _, note := range notes {
183 rows = append(rows, map[string]any{
184 "id": note.ID, "body": note.Body, "author": note.Author,
185 "file_path": note.FilePath, "line_start": note.LineStart, "line_end": note.LineEnd,
186 "suggestion": note.Suggestion, "parent_id": note.ParentID, "created_at": rfcTime(note.CreatedAt),
187 })
188 }
189 page, per := pageQuery(r)
190 writePage(w, r, slicePage(rows, page, per), len(rows), page, per)
191 return
192 }
193 var body struct {
194 Body string `json:"body"`
195 Path string `json:"path"`
196 LineStart int `json:"line_start"`
197 LineEnd int `json:"line_end"`
198 ParentID int64 `json:"parent_id"`
199 }
200 if err := readJSON(r, &body); err != nil {
201 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
202 return
203 }
204 note, err := s.opAddNote(r, apiUser(r), repo, n, body.Body, body.Path, body.LineStart, body.LineEnd, body.ParentID)
205 if !s.apiOK(w, r, err) {
206 return
207 }
208 writeJSON(w, http.StatusCreated, map[string]any{"id": note.ID})
209}
210
211func (s *Server) apiReview(w http.ResponseWriter, r *http.Request) {
212 repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper)
213 if !ok {
214 return
215 }
216 n, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
217 if err != nil {
218 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
219 return
220 }
221 var body struct {
222 Status string `json:"status"`
223 }
224 if err := readJSON(r, &body); err != nil {
225 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
226 return
227 }
228 if !s.apiOK(w, r, s.opReview(r.Context(), apiUser(r), repo, n, body.Status)) {
229 return
230 }
231 writeJSON(w, http.StatusOK, map[string]any{"status": body.Status})
232}
233
234func (s *Server) apiDismissReview(w http.ResponseWriter, r *http.Request) {
235 repo, _, ok := s.apiRepo(w, r, access.RoleMaintainer)
236 if !ok {
237 return
238 }
239 n, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
240 if err != nil {
241 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
242 return
243 }
244 var body struct {
245 UserID int64 `json:"user_id"`
246 }
247 if err := readJSON(r, &body); err != nil {
248 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
249 return
250 }
251 if !s.apiOK(w, r, s.opDismissReview(r.Context(), apiUser(r), repo, n, body.UserID)) {
252 return
253 }
254 writeJSON(w, http.StatusOK, map[string]any{"status": "dismissed"})
255}
256
257func (s *Server) apiSuggestions(w http.ResponseWriter, r *http.Request) {
258 repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper)
259 if !ok {
260 return
261 }
262 n, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
263 if err != nil {
264 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
265 return
266 }
267 var body struct {
268 Title string `json:"title"`
269 Description string `json:"description"`
270 IDs []int64 `json:"ids"`
271 }
272 if err := readJSON(r, &body); err != nil {
273 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
274 return
275 }
276 if !s.apiOK(w, r, s.opApplySuggestions(r.Context(), apiUser(r), repo, n, body.Title, body.Description, body.IDs)) {
277 return
278 }
279 writeJSON(w, http.StatusOK, map[string]any{"applied": len(body.IDs)})
280}
281
282func (s *Server) apiMerge(w http.ResponseWriter, r *http.Request) {
283 repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper)
284 if !ok {
285 return
286 }
287 n, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
288 if err != nil {
289 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
290 return
291 }
292 var body struct {
293 Remove *bool `json:"remove_source_branch"`
294 Squash *bool `json:"squash"`
295 Message *string `json:"squash_commit_message"`
296 }
297 if err := readJSON(r, &body); err != nil {
298 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
299 return
300 }
301 out, err := s.opMergeMR(r, apiUser(r), repo, n, mergeChoice{Remove: body.Remove, Squash: body.Squash, Message: body.Message})
302 if !s.apiOK(w, r, err) {
303 return
304 }
305 writeJSON(w, http.StatusOK, map[string]any{
306 "state": "merged", "source_branch_removed": out.Removed, "source_branch_skip": out.Skip,
307 "web_url": s.pageURL(repo, "/-/merge-requests/"+strconv.FormatInt(n, 10)),
308 })
309}
310
311func (s *Server) apiCloseMR(w http.ResponseWriter, r *http.Request) {
312 s.apiSetMR(w, r, false)
313}
314
315func (s *Server) apiReopenMR(w http.ResponseWriter, r *http.Request) {
316 s.apiSetMR(w, r, true)
317}
318
319func (s *Server) apiSetMR(w http.ResponseWriter, r *http.Request, reopen bool) {
320 repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
321 if !ok {
322 return
323 }
324 n, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
325 if err != nil {
326 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
327 return
328 }
329 if !s.apiOK(w, r, s.opCloseMR(r.Context(), apiUser(r), repo, n, reopen)) {
330 return
331 }
332 state := "closed"
333 if reopen {
334 state = "open"
335 }
336 writeJSON(w, http.StatusOK, map[string]any{
337 "state": state, "web_url": s.pageURL(repo, "/-/merge-requests/"+strconv.FormatInt(n, 10)),
338 })
339}
340
341func (s *Server) pipeJSON(repo store.Repo, p store.Pipeline) map[string]any {
342 return map[string]any{
343 "id": p.ID, "sha": p.CommitSHA, "ref": p.Ref, "status": s.pipeStatusFor(p), "source": p.Source,
344 "actor": p.Actor, "created_at": rfcTime(p.CreatedAt), "started_at": rfcTime(p.StartedAt), "finished_at": rfcTime(p.FinishedAt),
345 "web_url": s.pageURL(repo, "/-/pipelines/"+strconv.FormatInt(p.ID, 10)),
346 }
347}
348
349// pipeJSONJobs is pipeJSON met cancel_reason en display_status, die de
350// jobs nodig hebben. status blijft canceled voor oude clients.
351func (s *Server) pipeJSONJobs(ctx context.Context, repo store.Repo, p store.Pipeline) map[string]any {
352 out := s.pipeJSON(repo, p)
353 st := s.pipeStatusFor(p)
354 out["display_status"] = st
355 out["cancel_reason"] = nil
356 if st == "canceled" {
357 jobs, _ := s.Store.JobsByPipeline(ctx, p.ID)
358 out["cancel_reason"] = "manual"
359 if store.PipelineObsolete(jobs) {
360 out["cancel_reason"] = "superseded"
361 out["display_status"] = "obsolete"
362 }
363 }
364 return out
365}
366
367func (s *Server) jobJSON(ctx context.Context, j store.Job) map[string]any {
368 out := map[string]any{
369 "id": j.ID, "name": j.Name, "stage": j.Stage, "status": j.Status, "when": j.When,
370 "allow_failure": j.AllowFailure, "started_at": rfcTime(j.StartedAt), "finished_at": rfcTime(j.FinishedAt),
371 "runner": nil, "display_status": j.Status, "cancel_reason": nil, "failure_reason": nil,
372 }
373 if r := j.CancelReason(); r != "" {
374 out["cancel_reason"] = r
375 if j.Obsolete() {
376 out["display_status"] = "obsolete"
377 }
378 }
379 if r := j.FailureReason(); r != "" {
380 out["failure_reason"] = r
381 }
382 if jr := s.Store.JobRun(ctx, j.ID); jr.RunnerName != "" {
383 kind := "builtin"
384 if jr.RunnerID > 0 {
385 kind = "remote"
386 }
387 out["runner"] = map[string]any{"id": jr.RunnerID, "name": jr.RunnerName, "kind": kind}
388 }
389 return out
390}
391
392func (s *Server) apiPipelines(w http.ResponseWriter, r *http.Request) {
393 repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
394 if !ok {
395 return
396 }
397 if r.Method == http.MethodPost {
398 var body struct {
399 Ref string `json:"ref"`
400 }
401 if err := readJSON(r, &body); err != nil {
402 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
403 return
404 }
405 id, err := s.opRunPipeline(r.Context(), apiUser(r), repo, body.Ref, "api")
406 if !s.apiOK(w, r, err) {
407 return
408 }
409 if p, err := s.Store.PipelineByID(r.Context(), repo.ID, id); err == nil {
410 writeJSON(w, http.StatusCreated, s.pipeJSON(repo, p))
411 return
412 }
413 writeJSON(w, http.StatusCreated, map[string]any{
414 "id": id, "web_url": s.pageURL(repo, "/-/pipelines/"+strconv.FormatInt(id, 10)),
415 })
416 return
417 }
418 f, err := s.pipelineFilter(r, repo)
419 if !s.apiOK(w, r, err) {
420 return
421 }
422 list, err := s.Store.FindPipelines(r.Context(), repo.ID, f)
423 if !s.apiOK(w, r, err) {
424 return
425 }
426 page, per := pageQuery(r)
427 rows := make([]map[string]any, 0, len(list))
428 for _, p := range list {
429 rows = append(rows, s.pipeJSONJobs(r.Context(), repo, p))
430 }
431 writePage(w, r, slicePage(rows, page, per), len(rows), page, per)
432}
433
434func (s *Server) apiPipeline(w http.ResponseWriter, r *http.Request) {
435 repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
436 if !ok {
437 return
438 }
439 id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
440 if err != nil {
441 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
442 return
443 }
444 p, err := s.Store.PipelineByID(r.Context(), repo.ID, id)
445 if err != nil {
446 s.writeAPIErr(w, r, notFound(err))
447 return
448 }
449 writeJSON(w, http.StatusOK, s.pipeJSONJobs(r.Context(), repo, p))
450}
451
452func (s *Server) apiRetryPipeline(w http.ResponseWriter, r *http.Request) {
453 repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper)
454 if !ok {
455 return
456 }
457 pipeID, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
458 if err != nil {
459 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
460 return
461 }
462 var body struct {
463 Mode string `json:"mode"`
464 }
465 if err := readJSON(r, &body); err != nil {
466 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
467 return
468 }
469 id, err := s.opRetryPipeline(r.Context(), apiUser(r), repo, pipeID, body.Mode)
470 if !s.apiOK(w, r, err) {
471 return
472 }
473 p, err := s.Store.PipelineByID(r.Context(), repo.ID, id)
474 if err != nil {
475 s.writeAPIErr(w, r, notFound(err))
476 return
477 }
478 code := http.StatusOK
479 if body.Mode == "all" {
480 code = http.StatusCreated
481 }
482 writeJSON(w, code, s.pipeJSON(repo, p))
483}
484
485func (s *Server) apiCancelPipeline(w http.ResponseWriter, r *http.Request) {
486 repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper)
487 if !ok {
488 return
489 }
490 id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
491 if err != nil {
492 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
493 return
494 }
495 if !s.apiOK(w, r, s.opCancelPipeline(r.Context(), apiUser(r), repo, id)) {
496 return
497 }
498 if p, err := s.Store.PipelineByID(r.Context(), repo.ID, id); err == nil {
499 writeJSON(w, http.StatusOK, s.pipeJSON(repo, p))
500 return
501 }
502 writeJSON(w, http.StatusOK, map[string]any{
503 "id": id, "status": "canceled", "web_url": s.pageURL(repo, "/-/pipelines/"+strconv.FormatInt(id, 10)),
504 })
505}
506
507func (s *Server) apiJobs(w http.ResponseWriter, r *http.Request) {
508 repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
509 if !ok {
510 return
511 }
512 id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
513 if err != nil {
514 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
515 return
516 }
517 p, err := s.Store.PipelineByID(r.Context(), repo.ID, id)
518 if err != nil {
519 s.writeAPIErr(w, r, notFound(err))
520 return
521 }
522 jobs, err := s.Store.JobsByPipeline(r.Context(), p.ID)
523 if !s.apiOK(w, r, err) {
524 return
525 }
526 rows := make([]map[string]any, 0, len(jobs))
527 for _, j := range jobs {
528 rows = append(rows, s.jobJSON(r.Context(), j))
529 }
530 writeJSON(w, http.StatusOK, rows)
531}
532
533func (s *Server) apiJob(w http.ResponseWriter, r *http.Request) {
534 _, job, ok := s.apiFindJob(w, r)
535 if !ok {
536 return
537 }
538 writeJSON(w, http.StatusOK, s.jobJSON(r.Context(), job))
539}
540
541func (s *Server) apiJobLog(w http.ResponseWriter, r *http.Request) {
542 _, job, ok := s.apiFindJob(w, r)
543 if !ok {
544 return
545 }
546 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
547 w.WriteHeader(http.StatusOK)
548 _, _ = w.Write([]byte(job.Log))
549}
550
551func (s *Server) apiJobAction(w http.ResponseWriter, r *http.Request, action string) {
552 repo, p, job, ok := s.apiFindJobFull(w, r, access.RoleDeveloper)
553 if !ok {
554 return
555 }
556 updated, err := s.opJobAction(r.Context(), apiUser(r), repo, p.ID, job.ID, action)
557 if !s.apiOK(w, r, err) {
558 return
559 }
560 writeJSON(w, http.StatusOK, s.jobJSON(r.Context(), updated))
561}
562
563func (s *Server) apiPlayJob(w http.ResponseWriter, r *http.Request) { s.apiJobAction(w, r, "play") }
564func (s *Server) apiRetryJob(w http.ResponseWriter, r *http.Request) {
565 s.apiJobAction(w, r, "retry")
566}
567func (s *Server) apiCancelJob(w http.ResponseWriter, r *http.Request) {
568 s.apiJobAction(w, r, "cancel")
569}
570
571func (s *Server) apiFindJob(w http.ResponseWriter, r *http.Request) (store.Pipeline, store.Job, bool) {
572 _, p, job, ok := s.apiFindJobFull(w, r, access.RoleReadonly)
573 return p, job, ok
574}
575
576func (s *Server) apiFindJobFull(w http.ResponseWriter, r *http.Request, min access.Role) (store.Repo, store.Pipeline, store.Job, bool) {
577 repo, _, ok := s.apiRepo(w, r, min)
578 if !ok {
579 return store.Repo{}, store.Pipeline{}, store.Job{}, false
580 }
581 pid, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
582 if err != nil {
583 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
584 return store.Repo{}, store.Pipeline{}, store.Job{}, false
585 }
586 jid, err := strconv.ParseInt(r.PathValue("job"), 10, 64)
587 if err != nil {
588 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
589 return store.Repo{}, store.Pipeline{}, store.Job{}, false
590 }
591 p, err := s.Store.PipelineByID(r.Context(), repo.ID, pid)
592 if err != nil {
593 s.writeAPIErr(w, r, notFound(err))
594 return store.Repo{}, store.Pipeline{}, store.Job{}, false
595 }
596 jobs, _ := s.Store.JobsByPipeline(r.Context(), p.ID)
597 for _, j := range jobs {
598 if j.ID == jid {
599 return repo, p, j, true
600 }
601 }
602 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
603 return store.Repo{}, store.Pipeline{}, store.Job{}, false
604}
605
606func (s *Server) apiArtifacts(w http.ResponseWriter, r *http.Request) {
607 _, job, ok := s.apiFindJob(w, r)
608 if !ok {
609 return
610 }
611 list, err := s.Store.ListArtifacts(r.Context(), job.ID)
612 if !s.apiOK(w, r, err) {
613 return
614 }
615 rows := make([]map[string]any, 0, len(list))
616 for _, a := range list {
617 rows = append(rows, map[string]any{"path": a.Path, "size": a.Size})
618 }
619 writeJSON(w, http.StatusOK, rows)
620}
621
622func (s *Server) apiArtifact(w http.ResponseWriter, r *http.Request) {
623 _, job, ok := s.apiFindJob(w, r)
624 if !ok {
625 return
626 }
627 want := r.PathValue("path")
628 if strings.Contains(want, "..") {
629 s.writeAPIErr(w, r, fail(400, i18n.E("err.sugFile")))
630 return
631 }
632 list, err := s.Store.ListArtifacts(r.Context(), job.ID)
633 if !s.apiOK(w, r, err) {
634 return
635 }
636 for _, a := range list {
637 if a.Path == want {
638 http.ServeFile(w, r, a.StoragePath)
639 return
640 }
641 }
642 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
643}
644
645func (s *Server) apiCIFile(w http.ResponseWriter, r *http.Request) {
646 repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
647 if !ok {
648 return
649 }
650 if r.Method == http.MethodPut {
651 var body struct {
652 Branch string `json:"branch"`
653 Base string `json:"base"`
654 Message string `json:"message"`
655 Content string `json:"content"`
656 OpenMR bool `json:"open_mr"`
657 }
658 if err := readJSON(r, &body); err != nil {
659 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
660 return
661 }
662 sha, number, err := s.opSaveCI(r.Context(), apiUser(r), repo, body.Base, body.Branch, body.Message, body.Content, body.OpenMR)
663 if !s.apiOK(w, r, err) {
664 return
665 }
666 writeJSON(w, http.StatusOK, map[string]any{"id": sha, "merge_request": number})
667 return
668 }
669 body, err := s.opCIFile(r.Context(), repo, r.URL.Query().Get("ref"))
670 if !s.apiOK(w, r, err) {
671 return
672 }
673 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
674 w.WriteHeader(http.StatusOK)
675 _, _ = w.Write([]byte(body))
676}
677
678func (s *Server) apiLintCI(w http.ResponseWriter, r *http.Request) {
679 repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
680 if !ok {
681 return
682 }
683 var body struct {
684 Body string `json:"body"`
685 Ref string `json:"ref"`
686 }
687 if err := readJSON(r, &body); err != nil {
688 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
689 return
690 }
691 out, err := s.opLintCI(r, repo, body.Body, body.Ref)
692 if !s.apiOK(w, r, err) {
693 return
694 }
695 writeJSON(w, http.StatusOK, out)
696}
697
698func (s *Server) apiPresets(w http.ResponseWriter, r *http.Request) {
699 set, err := images.Effective(s.Cfg.CI.ImageOverrides())
700 if err != nil {
701 s.writeAPIErr(w, r, fail(500, err))
702 return
703 }
704 rows := make([]map[string]any, 0, len(set))
705 for _, p := range set {
706 rows = append(rows, map[string]any{"name": "bluegit/" + p.Name, "from": p.From, "runtime": p.Runtime, "tools": p.Tools, "direct": p.Direct})
707 }
708 writeJSON(w, http.StatusOK, rows)
709}
710
711func (s *Server) apiReleases(w http.ResponseWriter, r *http.Request) {
712 repo, role, ok := s.apiRepoReleases(w, r)
713 if !ok {
714 return
715 }
716 list, err := s.Store.ListReleases(r.Context(), repo.ID)
717 if !s.apiOK(w, r, err) {
718 return
719 }
720 page, per := pageQuery(r)
721 rows := make([]map[string]any, 0, len(list))
722 for _, rel := range list {
723 assets := make([]map[string]any, 0, len(rel.Assets))
724 for _, a := range rel.Assets {
725 assets = append(assets, map[string]any{"name": a.Name, "size": a.Size})
726 }
727 row := map[string]any{
728 "id": rel.ID, "tag": rel.Tag, "commit": rel.CommitSHA, "name": rel.Name, "body": rel.Body,
729 "created_at": rfcTime(rel.CreatedAt), "assets": assets,
730 }
731 if releaseOnly(repo, role) {
732 delete(row, "commit") // geen verwijzing naar broncode voor niet-leden
733 }
734 rows = append(rows, row)
735 }
736 writePage(w, r, slicePage(rows, page, per), len(rows), page, per)
737}
738
739func (s *Server) apiReleaseAsset(w http.ResponseWriter, r *http.Request) {
740 repo, _, ok := s.apiRepoReleases(w, r)
741 if !ok {
742 return
743 }
744 rel, err := s.Store.ReleaseByTag(r.Context(), repo.ID, r.PathValue("tag"))
745 if err != nil {
746 s.writeAPIErr(w, r, notFound(err))
747 return
748 }
749 name := r.PathValue("name")
750 for _, a := range rel.Assets {
751 if a.Name == name {
752 w.Header().Set("Content-Disposition", "attachment; filename=\""+strings.ReplaceAll(name, "\"", "")+"\"")
753 http.ServeFile(w, r, a.StoragePath)
754 return
755 }
756 }
757 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
758}
759
760// pipelineFilter leest sha, ref en mr uit de query.
761// ref mag een branchnaam zijn (refs/heads/ en refs/tags/ worden geprobeerd)
762// of een volledige ref. mr is het MR-nummer: pipelines van die MR plus
763// pushes naar de bronbranch.
764func (s *Server) pipelineFilter(r *http.Request, repo store.Repo) (store.PipelineFilter, error) {
765 q := r.URL.Query()
766 var f store.PipelineFilter
767 if sha := strings.TrimSpace(q.Get("sha")); sha != "" {
768 if len(sha) < 7 || len(sha) > 40 || strings.Trim(strings.ToLower(sha), "0123456789abcdef") != "" {
769 return f, fail(400, i18n.E("err.badSHA"))
770 }
771 f.SHA = sha
772 }
773 if ref := strings.TrimSpace(q.Get("ref")); ref != "" {
774 if strings.HasPrefix(ref, "refs/") {
775 f.Refs = []string{ref}
776 } else {
777 f.Refs = []string{"refs/heads/" + ref, "refs/tags/" + ref}
778 }
779 }
780 if raw := strings.TrimSpace(q.Get("mr")); raw != "" {
781 n, err := strconv.ParseInt(raw, 10, 64)
782 if err != nil || n < 1 {
783 return f, fail(400, i18n.E("err.notFound"))
784 }
785 mr, err := s.Store.MergeRequestByNumber(r.Context(), repo.ID, n)
786 if err != nil {
787 return f, notFound(err)
788 }
789 if len(f.Refs) > 0 {
790 return f, fail(400, i18n.E("err.pipeFilter"))
791 }
792 f.MRID = mr.ID
793 f.Refs = []string{"refs/heads/" + mr.SourceBranch}
794 }
795 return f, nil
796}