BlueGit

timfa bluegit

Files

bluegit / internal / server / api_flow.go

api_flow.go

api_flow.go 23.5 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 out["waiting_for"] = nil
357 if blk, ok := s.protectedBlocker(p); ok && st == "waiting_for_job" {
358 out["waiting_for"] = map[string]any{"job_id": blk.ID, "job_name": blk.Name, "pipeline_id": blk.PipelineID}
359 }
360 if st == "canceled" {
361 jobs, _ := s.Store.JobsByPipeline(ctx, p.ID)
362 out["cancel_reason"] = "manual"
363 if store.PipelineObsolete(jobs) {
364 out["cancel_reason"] = "superseded"
365 out["display_status"] = "obsolete"
366 }
367 }
368 return out
369}
370
371func (s *Server) jobJSON(ctx context.Context, j store.Job) map[string]any {
372 out := map[string]any{
373 "id": j.ID, "name": j.Name, "stage": j.Stage, "status": j.Status, "when": j.When,
374 "allow_failure": j.AllowFailure, "started_at": rfcTime(j.StartedAt), "finished_at": rfcTime(j.FinishedAt),
375 "runner": nil, "do_not_interrupt": j.DoNotInterrupt, "display_status": j.Status, "cancel_reason": nil, "failure_reason": nil,
376 }
377 if r := j.CancelReason(); r != "" {
378 out["cancel_reason"] = r
379 if j.Obsolete() {
380 out["display_status"] = "obsolete"
381 }
382 }
383 if r := j.FailureReason(); r != "" {
384 out["failure_reason"] = r
385 }
386 if jr := s.Store.JobRun(ctx, j.ID); jr.RunnerName != "" {
387 kind := "builtin"
388 if jr.RunnerID > 0 {
389 kind = "remote"
390 }
391 out["runner"] = map[string]any{"id": jr.RunnerID, "name": jr.RunnerName, "kind": kind}
392 }
393 return out
394}
395
396func (s *Server) apiPipelines(w http.ResponseWriter, r *http.Request) {
397 repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
398 if !ok {
399 return
400 }
401 if r.Method == http.MethodPost {
402 var body struct {
403 Ref string `json:"ref"`
404 }
405 if err := readJSON(r, &body); err != nil {
406 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
407 return
408 }
409 id, err := s.opRunPipeline(r.Context(), apiUser(r), repo, body.Ref, "api")
410 if !s.apiOK(w, r, err) {
411 return
412 }
413 if p, err := s.Store.PipelineByID(r.Context(), repo.ID, id); err == nil {
414 writeJSON(w, http.StatusCreated, s.pipeJSON(repo, p))
415 return
416 }
417 writeJSON(w, http.StatusCreated, map[string]any{
418 "id": id, "web_url": s.pageURL(repo, "/-/pipelines/"+strconv.FormatInt(id, 10)),
419 })
420 return
421 }
422 f, err := s.pipelineFilter(r, repo)
423 if !s.apiOK(w, r, err) {
424 return
425 }
426 list, err := s.Store.FindPipelines(r.Context(), repo.ID, f)
427 if !s.apiOK(w, r, err) {
428 return
429 }
430 page, per := pageQuery(r)
431 rows := make([]map[string]any, 0, len(list))
432 for _, p := range list {
433 rows = append(rows, s.pipeJSONJobs(r.Context(), repo, p))
434 }
435 writePage(w, r, slicePage(rows, page, per), len(rows), page, per)
436}
437
438func (s *Server) apiPipeline(w http.ResponseWriter, r *http.Request) {
439 repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
440 if !ok {
441 return
442 }
443 id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
444 if err != nil {
445 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
446 return
447 }
448 p, err := s.Store.PipelineByID(r.Context(), repo.ID, id)
449 if err != nil {
450 s.writeAPIErr(w, r, notFound(err))
451 return
452 }
453 writeJSON(w, http.StatusOK, s.pipeJSONJobs(r.Context(), repo, p))
454}
455
456func (s *Server) apiRetryPipeline(w http.ResponseWriter, r *http.Request) {
457 repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper)
458 if !ok {
459 return
460 }
461 pipeID, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
462 if err != nil {
463 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
464 return
465 }
466 var body struct {
467 Mode string `json:"mode"`
468 }
469 if err := readJSON(r, &body); err != nil {
470 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
471 return
472 }
473 id, err := s.opRetryPipeline(r.Context(), apiUser(r), repo, pipeID, body.Mode)
474 if !s.apiOK(w, r, err) {
475 return
476 }
477 p, err := s.Store.PipelineByID(r.Context(), repo.ID, id)
478 if err != nil {
479 s.writeAPIErr(w, r, notFound(err))
480 return
481 }
482 code := http.StatusOK
483 if body.Mode == "all" {
484 code = http.StatusCreated
485 }
486 writeJSON(w, code, s.pipeJSON(repo, p))
487}
488
489func (s *Server) apiCancelPipeline(w http.ResponseWriter, r *http.Request) {
490 repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper)
491 if !ok {
492 return
493 }
494 id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
495 if err != nil {
496 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
497 return
498 }
499 if !s.apiOK(w, r, s.opCancelPipeline(r.Context(), apiUser(r), repo, id, forceParam(r))) {
500 return
501 }
502 if p, err := s.Store.PipelineByID(r.Context(), repo.ID, id); err == nil {
503 writeJSON(w, http.StatusOK, s.pipeJSON(repo, p))
504 return
505 }
506 writeJSON(w, http.StatusOK, map[string]any{
507 "id": id, "status": "canceled", "web_url": s.pageURL(repo, "/-/pipelines/"+strconv.FormatInt(id, 10)),
508 })
509}
510
511func (s *Server) apiJobs(w http.ResponseWriter, r *http.Request) {
512 repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
513 if !ok {
514 return
515 }
516 id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
517 if err != nil {
518 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
519 return
520 }
521 p, err := s.Store.PipelineByID(r.Context(), repo.ID, id)
522 if err != nil {
523 s.writeAPIErr(w, r, notFound(err))
524 return
525 }
526 jobs, err := s.Store.JobsByPipeline(r.Context(), p.ID)
527 if !s.apiOK(w, r, err) {
528 return
529 }
530 rows := make([]map[string]any, 0, len(jobs))
531 for _, j := range jobs {
532 rows = append(rows, s.jobJSON(r.Context(), j))
533 }
534 writeJSON(w, http.StatusOK, rows)
535}
536
537func (s *Server) apiJob(w http.ResponseWriter, r *http.Request) {
538 _, job, ok := s.apiFindJob(w, r)
539 if !ok {
540 return
541 }
542 writeJSON(w, http.StatusOK, s.jobJSON(r.Context(), job))
543}
544
545func (s *Server) apiJobLog(w http.ResponseWriter, r *http.Request) {
546 _, job, ok := s.apiFindJob(w, r)
547 if !ok {
548 return
549 }
550 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
551 w.WriteHeader(http.StatusOK)
552 _, _ = w.Write([]byte(job.Log))
553}
554
555func (s *Server) apiJobAction(w http.ResponseWriter, r *http.Request, action string) {
556 repo, p, job, ok := s.apiFindJobFull(w, r, access.RoleDeveloper)
557 if !ok {
558 return
559 }
560 updated, err := s.opJobActionForce(r.Context(), apiUser(r), repo, p.ID, job.ID, action, action == "cancel" && forceParam(r))
561 if !s.apiOK(w, r, err) {
562 return
563 }
564 writeJSON(w, http.StatusOK, s.jobJSON(r.Context(), updated))
565}
566
567func (s *Server) apiPlayJob(w http.ResponseWriter, r *http.Request) { s.apiJobAction(w, r, "play") }
568func (s *Server) apiRetryJob(w http.ResponseWriter, r *http.Request) {
569 s.apiJobAction(w, r, "retry")
570}
571func (s *Server) apiCancelJob(w http.ResponseWriter, r *http.Request) {
572 s.apiJobAction(w, r, "cancel")
573}
574
575func (s *Server) apiFindJob(w http.ResponseWriter, r *http.Request) (store.Pipeline, store.Job, bool) {
576 _, p, job, ok := s.apiFindJobFull(w, r, access.RoleReadonly)
577 return p, job, ok
578}
579
580func (s *Server) apiFindJobFull(w http.ResponseWriter, r *http.Request, min access.Role) (store.Repo, store.Pipeline, store.Job, bool) {
581 repo, _, ok := s.apiRepo(w, r, min)
582 if !ok {
583 return store.Repo{}, store.Pipeline{}, store.Job{}, false
584 }
585 pid, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
586 if err != nil {
587 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
588 return store.Repo{}, store.Pipeline{}, store.Job{}, false
589 }
590 jid, err := strconv.ParseInt(r.PathValue("job"), 10, 64)
591 if err != nil {
592 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
593 return store.Repo{}, store.Pipeline{}, store.Job{}, false
594 }
595 p, err := s.Store.PipelineByID(r.Context(), repo.ID, pid)
596 if err != nil {
597 s.writeAPIErr(w, r, notFound(err))
598 return store.Repo{}, store.Pipeline{}, store.Job{}, false
599 }
600 jobs, _ := s.Store.JobsByPipeline(r.Context(), p.ID)
601 for _, j := range jobs {
602 if j.ID == jid {
603 return repo, p, j, true
604 }
605 }
606 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
607 return store.Repo{}, store.Pipeline{}, store.Job{}, false
608}
609
610func (s *Server) apiArtifacts(w http.ResponseWriter, r *http.Request) {
611 _, job, ok := s.apiFindJob(w, r)
612 if !ok {
613 return
614 }
615 list, err := s.Store.ListArtifacts(r.Context(), job.ID)
616 if !s.apiOK(w, r, err) {
617 return
618 }
619 rows := make([]map[string]any, 0, len(list))
620 for _, a := range list {
621 rows = append(rows, map[string]any{"path": a.Path, "size": a.Size})
622 }
623 writeJSON(w, http.StatusOK, rows)
624}
625
626func (s *Server) apiArtifact(w http.ResponseWriter, r *http.Request) {
627 _, job, ok := s.apiFindJob(w, r)
628 if !ok {
629 return
630 }
631 want := r.PathValue("path")
632 if strings.Contains(want, "..") {
633 s.writeAPIErr(w, r, fail(400, i18n.E("err.sugFile")))
634 return
635 }
636 list, err := s.Store.ListArtifacts(r.Context(), job.ID)
637 if !s.apiOK(w, r, err) {
638 return
639 }
640 for _, a := range list {
641 if a.Path == want {
642 http.ServeFile(w, r, a.StoragePath)
643 return
644 }
645 }
646 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
647}
648
649func (s *Server) apiCIFile(w http.ResponseWriter, r *http.Request) {
650 repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
651 if !ok {
652 return
653 }
654 if r.Method == http.MethodPut {
655 var body struct {
656 Branch string `json:"branch"`
657 Base string `json:"base"`
658 Message string `json:"message"`
659 Content string `json:"content"`
660 OpenMR bool `json:"open_mr"`
661 }
662 if err := readJSON(r, &body); err != nil {
663 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
664 return
665 }
666 sha, number, err := s.opSaveCI(r.Context(), apiUser(r), repo, body.Base, body.Branch, body.Message, body.Content, body.OpenMR)
667 if !s.apiOK(w, r, err) {
668 return
669 }
670 writeJSON(w, http.StatusOK, map[string]any{"id": sha, "merge_request": number})
671 return
672 }
673 body, err := s.opCIFile(r.Context(), repo, r.URL.Query().Get("ref"))
674 if !s.apiOK(w, r, err) {
675 return
676 }
677 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
678 w.WriteHeader(http.StatusOK)
679 _, _ = w.Write([]byte(body))
680}
681
682func (s *Server) apiLintCI(w http.ResponseWriter, r *http.Request) {
683 repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
684 if !ok {
685 return
686 }
687 var body struct {
688 Body string `json:"body"`
689 Ref string `json:"ref"`
690 }
691 if err := readJSON(r, &body); err != nil {
692 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
693 return
694 }
695 out, err := s.opLintCI(r, repo, body.Body, body.Ref)
696 if !s.apiOK(w, r, err) {
697 return
698 }
699 writeJSON(w, http.StatusOK, out)
700}
701
702func (s *Server) apiPresets(w http.ResponseWriter, r *http.Request) {
703 set, err := images.Effective(s.Cfg.CI.ImageOverrides())
704 if err != nil {
705 s.writeAPIErr(w, r, fail(500, err))
706 return
707 }
708 rows := make([]map[string]any, 0, len(set))
709 for _, p := range set {
710 rows = append(rows, map[string]any{"name": "bluegit/" + p.Name, "from": p.From, "runtime": p.Runtime, "tools": p.Tools, "direct": p.Direct})
711 }
712 writeJSON(w, http.StatusOK, rows)
713}
714
715func (s *Server) apiReleases(w http.ResponseWriter, r *http.Request) {
716 repo, role, ok := s.apiRepoReleases(w, r)
717 if !ok {
718 return
719 }
720 list, err := s.Store.ListReleases(r.Context(), repo.ID)
721 if !s.apiOK(w, r, err) {
722 return
723 }
724 page, per := pageQuery(r)
725 rows := make([]map[string]any, 0, len(list))
726 for _, rel := range list {
727 assets := make([]map[string]any, 0, len(rel.Assets))
728 for _, a := range rel.Assets {
729 assets = append(assets, map[string]any{"name": a.Name, "size": a.Size})
730 }
731 row := map[string]any{
732 "id": rel.ID, "tag": rel.Tag, "commit": rel.CommitSHA, "name": rel.Name, "body": rel.Body,
733 "created_at": rfcTime(rel.CreatedAt), "assets": assets,
734 }
735 if releaseOnly(repo, role) {
736 delete(row, "commit") // geen verwijzing naar broncode voor niet-leden
737 }
738 rows = append(rows, row)
739 }
740 writePage(w, r, slicePage(rows, page, per), len(rows), page, per)
741}
742
743func (s *Server) apiReleaseAsset(w http.ResponseWriter, r *http.Request) {
744 repo, _, ok := s.apiRepoReleases(w, r)
745 if !ok {
746 return
747 }
748 rel, err := s.Store.ReleaseByTag(r.Context(), repo.ID, r.PathValue("tag"))
749 if err != nil {
750 s.writeAPIErr(w, r, notFound(err))
751 return
752 }
753 name := r.PathValue("name")
754 for _, a := range rel.Assets {
755 if a.Name == name {
756 w.Header().Set("Content-Disposition", "attachment; filename=\""+strings.ReplaceAll(name, "\"", "")+"\"")
757 http.ServeFile(w, r, a.StoragePath)
758 return
759 }
760 }
761 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
762}
763
764// pipelineFilter leest sha, ref en mr uit de query.
765// ref mag een branchnaam zijn (refs/heads/ en refs/tags/ worden geprobeerd)
766// of een volledige ref. mr is het MR-nummer: pipelines van die MR plus
767// pushes naar de bronbranch.
768func (s *Server) pipelineFilter(r *http.Request, repo store.Repo) (store.PipelineFilter, error) {
769 q := r.URL.Query()
770 var f store.PipelineFilter
771 if sha := strings.TrimSpace(q.Get("sha")); sha != "" {
772 if len(sha) < 7 || len(sha) > 40 || strings.Trim(strings.ToLower(sha), "0123456789abcdef") != "" {
773 return f, fail(400, i18n.E("err.badSHA"))
774 }
775 f.SHA = sha
776 }
777 if ref := strings.TrimSpace(q.Get("ref")); ref != "" {
778 if strings.HasPrefix(ref, "refs/") {
779 f.Refs = []string{ref}
780 } else {
781 f.Refs = []string{"refs/heads/" + ref, "refs/tags/" + ref}
782 }
783 }
784 if raw := strings.TrimSpace(q.Get("mr")); raw != "" {
785 n, err := strconv.ParseInt(raw, 10, 64)
786 if err != nil || n < 1 {
787 return f, fail(400, i18n.E("err.notFound"))
788 }
789 mr, err := s.Store.MergeRequestByNumber(r.Context(), repo.ID, n)
790 if err != nil {
791 return f, notFound(err)
792 }
793 if len(f.Refs) > 0 {
794 return f, fail(400, i18n.E("err.pipeFilter"))
795 }
796 f.MRID = mr.ID
797 f.Refs = []string{"refs/heads/" + mr.SourceBranch}
798 }
799 return f, nil
800}