BlueGit

timfa bluegit

Files

bluegit / internal / server / api_flow.go

api_flow.go

feat: bied dezelfde acties als de UI aan via /api/v1
timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa · 3 weeks ago
d89195e9 History
api_flow.go 16.4 KiB Download Raw
1package server
2
3import (
4 "net/http"
5 "strconv"
6 "strings"
7
8 "gitlab.com/Timfa/bluegit/internal/access"
9 "gitlab.com/Timfa/bluegit/internal/i18n"
10 "gitlab.com/Timfa/bluegit/internal/images"
11 "gitlab.com/Timfa/bluegit/internal/store"
12)
13
14func mrJSON(mr store.MergeRequest) map[string]any {
15 return map[string]any{
16 "id": mr.ID, "iid": mr.Number, "title": mr.Title, "description": mr.Description,
17 "source_branch": mr.SourceBranch, "target_branch": mr.TargetBranch,
18 "author": mr.Author, "state": mr.Status, "draft": mr.Draft, "labels": mr.Labels,
19 "created_at": rfcTime(mr.CreatedAt), "updated_at": rfcTime(mr.UpdatedAt),
20 }
21}
22
23func (s *Server) apiMRs(w http.ResponseWriter, r *http.Request) {
24 repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
25 if !ok {
26 return
27 }
28 if r.Method == http.MethodPost {
29 var body struct {
30 Title string `json:"title"`
31 Description string `json:"description"`
32 SourceBranch string `json:"source_branch"`
33 TargetBranch string `json:"target_branch"`
34 Draft bool `json:"draft"`
35 }
36 if err := readJSON(r, &body); err != nil {
37 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
38 return
39 }
40 mr, err := s.opCreateMR(r.Context(), apiUser(r), repo, body.Title, body.Description, body.SourceBranch, body.TargetBranch, body.Draft)
41 if !s.apiOK(w, r, err) {
42 return
43 }
44 writeJSON(w, http.StatusCreated, mrJSON(mr))
45 return
46 }
47 list, err := s.Store.ListMergeRequests(r.Context(), repo.ID)
48 if !s.apiOK(w, r, err) {
49 return
50 }
51 page, per := pageQuery(r)
52 rows := make([]map[string]any, 0, len(list))
53 for _, mr := range list {
54 rows = append(rows, mrJSON(mr))
55 }
56 writePage(w, r, slicePage(rows, page, per), len(rows), page, per)
57}
58
59func (s *Server) apiMR(w http.ResponseWriter, r *http.Request) {
60 repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
61 if !ok {
62 return
63 }
64 n, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
65 if err != nil {
66 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
67 return
68 }
69 if r.Method == http.MethodPut {
70 var body struct {
71 Title string `json:"title"`
72 Description string `json:"description"`
73 Labels string `json:"labels"`
74 }
75 if err := readJSON(r, &body); err != nil {
76 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
77 return
78 }
79 mr, err := s.opUpdateMR(r.Context(), apiUser(r), repo, n, body.Title, body.Description, body.Labels)
80 if !s.apiOK(w, r, err) {
81 return
82 }
83 writeJSON(w, http.StatusOK, mrJSON(mr))
84 return
85 }
86 mr, err := s.Store.MergeRequestByNumber(r.Context(), repo.ID, n)
87 if err != nil {
88 s.writeAPIErr(w, r, notFound(err))
89 return
90 }
91 writeJSON(w, http.StatusOK, mrJSON(mr))
92}
93
94func (s *Server) apiMRNotes(w http.ResponseWriter, r *http.Request) {
95 repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
96 if !ok {
97 return
98 }
99 n, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
100 if err != nil {
101 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
102 return
103 }
104 if r.Method == http.MethodGet {
105 mr, err := s.Store.MergeRequestByNumber(r.Context(), repo.ID, n)
106 if err != nil {
107 s.writeAPIErr(w, r, notFound(err))
108 return
109 }
110 notes, err := s.Store.ListNotes(r.Context(), mr.ID)
111 if !s.apiOK(w, r, err) {
112 return
113 }
114 rows := make([]map[string]any, 0, len(notes))
115 for _, note := range notes {
116 rows = append(rows, map[string]any{
117 "id": note.ID, "body": note.Body, "author": note.Author,
118 "file_path": note.FilePath, "line_start": note.LineStart, "line_end": note.LineEnd,
119 "suggestion": note.Suggestion, "parent_id": note.ParentID, "created_at": rfcTime(note.CreatedAt),
120 })
121 }
122 page, per := pageQuery(r)
123 writePage(w, r, slicePage(rows, page, per), len(rows), page, per)
124 return
125 }
126 var body struct {
127 Body string `json:"body"`
128 Path string `json:"path"`
129 LineStart int `json:"line_start"`
130 LineEnd int `json:"line_end"`
131 ParentID int64 `json:"parent_id"`
132 }
133 if err := readJSON(r, &body); err != nil {
134 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
135 return
136 }
137 note, err := s.opAddNote(r, apiUser(r), repo, n, body.Body, body.Path, body.LineStart, body.LineEnd, body.ParentID)
138 if !s.apiOK(w, r, err) {
139 return
140 }
141 writeJSON(w, http.StatusCreated, map[string]any{"id": note.ID})
142}
143
144func (s *Server) apiReview(w http.ResponseWriter, r *http.Request) {
145 repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper)
146 if !ok {
147 return
148 }
149 n, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
150 if err != nil {
151 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
152 return
153 }
154 var body struct {
155 Status string `json:"status"`
156 }
157 if err := readJSON(r, &body); err != nil {
158 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
159 return
160 }
161 if !s.apiOK(w, r, s.opReview(r.Context(), apiUser(r), repo, n, body.Status)) {
162 return
163 }
164 writeJSON(w, http.StatusOK, map[string]any{"status": body.Status})
165}
166
167func (s *Server) apiDismissReview(w http.ResponseWriter, r *http.Request) {
168 repo, _, ok := s.apiRepo(w, r, access.RoleMaintainer)
169 if !ok {
170 return
171 }
172 n, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
173 if err != nil {
174 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
175 return
176 }
177 var body struct {
178 UserID int64 `json:"user_id"`
179 }
180 if err := readJSON(r, &body); err != nil {
181 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
182 return
183 }
184 if !s.apiOK(w, r, s.opDismissReview(r.Context(), apiUser(r), repo, n, body.UserID)) {
185 return
186 }
187 writeJSON(w, http.StatusOK, map[string]any{"status": "dismissed"})
188}
189
190func (s *Server) apiSuggestions(w http.ResponseWriter, r *http.Request) {
191 repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper)
192 if !ok {
193 return
194 }
195 n, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
196 if err != nil {
197 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
198 return
199 }
200 var body struct {
201 Title string `json:"title"`
202 Description string `json:"description"`
203 IDs []int64 `json:"ids"`
204 }
205 if err := readJSON(r, &body); err != nil {
206 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
207 return
208 }
209 if !s.apiOK(w, r, s.opApplySuggestions(r.Context(), apiUser(r), repo, n, body.Title, body.Description, body.IDs)) {
210 return
211 }
212 writeJSON(w, http.StatusOK, map[string]any{"applied": len(body.IDs)})
213}
214
215func (s *Server) apiMerge(w http.ResponseWriter, r *http.Request) {
216 repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper)
217 if !ok {
218 return
219 }
220 n, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
221 if err != nil {
222 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
223 return
224 }
225 if !s.apiOK(w, r, s.opMergeMR(r, apiUser(r), repo, n)) {
226 return
227 }
228 writeJSON(w, http.StatusOK, map[string]any{"state": "merged"})
229}
230
231func (s *Server) apiCloseMR(w http.ResponseWriter, r *http.Request) {
232 s.apiSetMR(w, r, false)
233}
234
235func (s *Server) apiReopenMR(w http.ResponseWriter, r *http.Request) {
236 s.apiSetMR(w, r, true)
237}
238
239func (s *Server) apiSetMR(w http.ResponseWriter, r *http.Request, reopen bool) {
240 repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
241 if !ok {
242 return
243 }
244 n, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
245 if err != nil {
246 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
247 return
248 }
249 if !s.apiOK(w, r, s.opCloseMR(r.Context(), apiUser(r), repo, n, reopen)) {
250 return
251 }
252 state := "closed"
253 if reopen {
254 state = "open"
255 }
256 writeJSON(w, http.StatusOK, map[string]any{"state": state})
257}
258
259func pipeJSON(p store.Pipeline) map[string]any {
260 return map[string]any{
261 "id": p.ID, "sha": p.CommitSHA, "ref": p.Ref, "status": p.Status, "source": p.Source,
262 "actor": p.Actor, "created_at": rfcTime(p.CreatedAt), "started_at": rfcTime(p.StartedAt), "finished_at": rfcTime(p.FinishedAt),
263 }
264}
265
266func jobJSON(j store.Job) map[string]any {
267 return map[string]any{
268 "id": j.ID, "name": j.Name, "stage": j.Stage, "status": j.Status, "when": j.When,
269 "allow_failure": j.AllowFailure, "started_at": rfcTime(j.StartedAt), "finished_at": rfcTime(j.FinishedAt),
270 }
271}
272
273func (s *Server) apiPipelines(w http.ResponseWriter, r *http.Request) {
274 repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
275 if !ok {
276 return
277 }
278 if r.Method == http.MethodPost {
279 var body struct {
280 Ref string `json:"ref"`
281 }
282 if err := readJSON(r, &body); err != nil {
283 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
284 return
285 }
286 id, err := s.opRunPipeline(r.Context(), apiUser(r), repo, body.Ref, "api")
287 if !s.apiOK(w, r, err) {
288 return
289 }
290 writeJSON(w, http.StatusCreated, map[string]any{"id": id})
291 return
292 }
293 list, err := s.Store.ListPipelines(r.Context(), repo.ID)
294 if !s.apiOK(w, r, err) {
295 return
296 }
297 page, per := pageQuery(r)
298 rows := make([]map[string]any, 0, len(list))
299 for _, p := range list {
300 rows = append(rows, pipeJSON(p))
301 }
302 writePage(w, r, slicePage(rows, page, per), len(rows), page, per)
303}
304
305func (s *Server) apiPipeline(w http.ResponseWriter, r *http.Request) {
306 repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
307 if !ok {
308 return
309 }
310 id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
311 if err != nil {
312 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
313 return
314 }
315 p, err := s.Store.PipelineByID(r.Context(), repo.ID, id)
316 if err != nil {
317 s.writeAPIErr(w, r, notFound(err))
318 return
319 }
320 writeJSON(w, http.StatusOK, pipeJSON(p))
321}
322
323func (s *Server) apiCancelPipeline(w http.ResponseWriter, r *http.Request) {
324 repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper)
325 if !ok {
326 return
327 }
328 id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
329 if err != nil {
330 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
331 return
332 }
333 if !s.apiOK(w, r, s.opCancelPipeline(r.Context(), apiUser(r), repo, id)) {
334 return
335 }
336 writeJSON(w, http.StatusOK, map[string]any{"id": id, "status": "canceled"})
337}
338
339func (s *Server) apiJobs(w http.ResponseWriter, r *http.Request) {
340 repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
341 if !ok {
342 return
343 }
344 id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
345 if err != nil {
346 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
347 return
348 }
349 p, err := s.Store.PipelineByID(r.Context(), repo.ID, id)
350 if err != nil {
351 s.writeAPIErr(w, r, notFound(err))
352 return
353 }
354 jobs, err := s.Store.JobsByPipeline(r.Context(), p.ID)
355 if !s.apiOK(w, r, err) {
356 return
357 }
358 rows := make([]map[string]any, 0, len(jobs))
359 for _, j := range jobs {
360 rows = append(rows, jobJSON(j))
361 }
362 writeJSON(w, http.StatusOK, rows)
363}
364
365func (s *Server) apiJob(w http.ResponseWriter, r *http.Request) {
366 _, job, ok := s.apiFindJob(w, r)
367 if !ok {
368 return
369 }
370 writeJSON(w, http.StatusOK, jobJSON(job))
371}
372
373func (s *Server) apiJobLog(w http.ResponseWriter, r *http.Request) {
374 _, job, ok := s.apiFindJob(w, r)
375 if !ok {
376 return
377 }
378 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
379 w.WriteHeader(http.StatusOK)
380 _, _ = w.Write([]byte(job.Log))
381}
382
383func (s *Server) apiJobAction(w http.ResponseWriter, r *http.Request, action string) {
384 repo, p, job, ok := s.apiFindJobFull(w, r, access.RoleDeveloper)
385 if !ok {
386 return
387 }
388 updated, err := s.opJobAction(r.Context(), apiUser(r), repo, p.ID, job.ID, action)
389 if !s.apiOK(w, r, err) {
390 return
391 }
392 writeJSON(w, http.StatusOK, jobJSON(updated))
393}
394
395func (s *Server) apiPlayJob(w http.ResponseWriter, r *http.Request) { s.apiJobAction(w, r, "play") }
396func (s *Server) apiRetryJob(w http.ResponseWriter, r *http.Request) {
397 s.apiJobAction(w, r, "retry")
398}
399func (s *Server) apiCancelJob(w http.ResponseWriter, r *http.Request) {
400 s.apiJobAction(w, r, "cancel")
401}
402
403func (s *Server) apiFindJob(w http.ResponseWriter, r *http.Request) (store.Pipeline, store.Job, bool) {
404 _, p, job, ok := s.apiFindJobFull(w, r, access.RoleReadonly)
405 return p, job, ok
406}
407
408func (s *Server) apiFindJobFull(w http.ResponseWriter, r *http.Request, min access.Role) (store.Repo, store.Pipeline, store.Job, bool) {
409 repo, _, ok := s.apiRepo(w, r, min)
410 if !ok {
411 return store.Repo{}, store.Pipeline{}, store.Job{}, false
412 }
413 pid, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
414 if err != nil {
415 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
416 return store.Repo{}, store.Pipeline{}, store.Job{}, false
417 }
418 jid, err := strconv.ParseInt(r.PathValue("job"), 10, 64)
419 if err != nil {
420 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
421 return store.Repo{}, store.Pipeline{}, store.Job{}, false
422 }
423 p, err := s.Store.PipelineByID(r.Context(), repo.ID, pid)
424 if err != nil {
425 s.writeAPIErr(w, r, notFound(err))
426 return store.Repo{}, store.Pipeline{}, store.Job{}, false
427 }
428 jobs, _ := s.Store.JobsByPipeline(r.Context(), p.ID)
429 for _, j := range jobs {
430 if j.ID == jid {
431 return repo, p, j, true
432 }
433 }
434 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
435 return store.Repo{}, store.Pipeline{}, store.Job{}, false
436}
437
438func (s *Server) apiArtifacts(w http.ResponseWriter, r *http.Request) {
439 _, job, ok := s.apiFindJob(w, r)
440 if !ok {
441 return
442 }
443 list, err := s.Store.ListArtifacts(r.Context(), job.ID)
444 if !s.apiOK(w, r, err) {
445 return
446 }
447 rows := make([]map[string]any, 0, len(list))
448 for _, a := range list {
449 rows = append(rows, map[string]any{"path": a.Path, "size": a.Size})
450 }
451 writeJSON(w, http.StatusOK, rows)
452}
453
454func (s *Server) apiArtifact(w http.ResponseWriter, r *http.Request) {
455 _, job, ok := s.apiFindJob(w, r)
456 if !ok {
457 return
458 }
459 want := r.PathValue("path")
460 if strings.Contains(want, "..") {
461 s.writeAPIErr(w, r, fail(400, i18n.E("err.sugFile")))
462 return
463 }
464 list, err := s.Store.ListArtifacts(r.Context(), job.ID)
465 if !s.apiOK(w, r, err) {
466 return
467 }
468 for _, a := range list {
469 if a.Path == want {
470 http.ServeFile(w, r, a.StoragePath)
471 return
472 }
473 }
474 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
475}
476
477func (s *Server) apiCIFile(w http.ResponseWriter, r *http.Request) {
478 repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
479 if !ok {
480 return
481 }
482 if r.Method == http.MethodPut {
483 var body struct {
484 Branch string `json:"branch"`
485 Base string `json:"base"`
486 Message string `json:"message"`
487 Content string `json:"content"`
488 OpenMR bool `json:"open_mr"`
489 }
490 if err := readJSON(r, &body); err != nil {
491 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
492 return
493 }
494 sha, number, err := s.opSaveCI(r.Context(), apiUser(r), repo, body.Base, body.Branch, body.Message, body.Content, body.OpenMR)
495 if !s.apiOK(w, r, err) {
496 return
497 }
498 writeJSON(w, http.StatusOK, map[string]any{"id": sha, "merge_request": number})
499 return
500 }
501 body, err := s.opCIFile(r.Context(), repo, r.URL.Query().Get("ref"))
502 if !s.apiOK(w, r, err) {
503 return
504 }
505 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
506 w.WriteHeader(http.StatusOK)
507 _, _ = w.Write([]byte(body))
508}
509
510func (s *Server) apiLintCI(w http.ResponseWriter, r *http.Request) {
511 repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
512 if !ok {
513 return
514 }
515 var body struct {
516 Body string `json:"body"`
517 Ref string `json:"ref"`
518 }
519 if err := readJSON(r, &body); err != nil {
520 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
521 return
522 }
523 out, err := s.opLintCI(r, repo, body.Body, body.Ref)
524 if !s.apiOK(w, r, err) {
525 return
526 }
527 writeJSON(w, http.StatusOK, out)
528}
529
530func (s *Server) apiPresets(w http.ResponseWriter, r *http.Request) {
531 set, err := images.Effective(s.Cfg.CI.ImageOverrides())
532 if err != nil {
533 s.writeAPIErr(w, r, fail(500, err))
534 return
535 }
536 rows := make([]map[string]any, 0, len(set))
537 for _, p := range set {
538 rows = append(rows, map[string]any{"name": "bluegit/" + p.Name, "from": p.From, "runtime": p.Runtime, "tools": p.Tools, "direct": p.Direct})
539 }
540 writeJSON(w, http.StatusOK, rows)
541}
542
543func (s *Server) apiReleases(w http.ResponseWriter, r *http.Request) {
544 repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
545 if !ok {
546 return
547 }
548 list, err := s.Store.ListReleases(r.Context(), repo.ID)
549 if !s.apiOK(w, r, err) {
550 return
551 }
552 page, per := pageQuery(r)
553 rows := make([]map[string]any, 0, len(list))
554 for _, rel := range list {
555 assets := make([]map[string]any, 0, len(rel.Assets))
556 for _, a := range rel.Assets {
557 assets = append(assets, map[string]any{"name": a.Name, "size": a.Size})
558 }
559 rows = append(rows, map[string]any{
560 "id": rel.ID, "tag": rel.Tag, "commit": rel.CommitSHA, "name": rel.Name, "body": rel.Body,
561 "created_at": rfcTime(rel.CreatedAt), "assets": assets,
562 })
563 }
564 writePage(w, r, slicePage(rows, page, per), len(rows), page, per)
565}
566
567func (s *Server) apiReleaseAsset(w http.ResponseWriter, r *http.Request) {
568 repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
569 if !ok {
570 return
571 }
572 rel, err := s.Store.ReleaseByTag(r.Context(), repo.ID, r.PathValue("tag"))
573 if err != nil {
574 s.writeAPIErr(w, r, notFound(err))
575 return
576 }
577 name := r.PathValue("name")
578 for _, a := range rel.Assets {
579 if a.Name == name {
580 w.Header().Set("Content-Disposition", "attachment; filename=\""+strings.ReplaceAll(name, "\"", "")+"\"")
581 http.ServeFile(w, r, a.StoragePath)
582 return
583 }
584 }
585 s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound")))
586}