package server import ( "net/http" "strconv" "strings" "gitlab.com/Timfa/bluegit/internal/access" "gitlab.com/Timfa/bluegit/internal/i18n" "gitlab.com/Timfa/bluegit/internal/images" "gitlab.com/Timfa/bluegit/internal/store" ) func (s *Server) pageURL(repo store.Repo, suffix string) string { if !strings.HasPrefix(suffix, "/") { suffix = "/" + suffix } return strings.TrimRight(s.Cfg.BaseURL, "/") + "/" + repo.FullPath() + suffix } func (s *Server) mrJSON(repo store.Repo, mr store.MergeRequest) map[string]any { return map[string]any{ "id": mr.ID, "iid": mr.Number, "title": mr.Title, "description": mr.Description, "source_branch": mr.SourceBranch, "target_branch": mr.TargetBranch, "author": mr.Author, "state": mr.Status, "draft": mr.Draft, "labels": mr.Labels, "remove_source_branch": mr.RemoveSourceBranch, "squash": mr.Squash, "squash_commit_message": mr.SquashMessage, "web_url": s.pageURL(repo, "/-/merge-requests/"+strconv.FormatInt(mr.Number, 10)), "created_at": rfcTime(mr.CreatedAt), "updated_at": rfcTime(mr.UpdatedAt), } } func (s *Server) apiMRs(w http.ResponseWriter, r *http.Request) { repo, _, ok := s.apiRepo(w, r, access.RoleReadonly) if !ok { return } if r.Method == http.MethodPost { var body struct { Title string `json:"title"` Description string `json:"description"` SourceBranch string `json:"source_branch"` TargetBranch string `json:"target_branch"` Draft bool `json:"draft"` Remove *bool `json:"remove_source_branch"` Squash *bool `json:"squash"` Message *string `json:"squash_commit_message"` } if err := readJSON(r, &body); err != nil { s.writeAPIErr(w, r, fail(400, i18n.E("err.json"))) return } mr, err := s.opCreateMR(r.Context(), apiUser(r), repo, body.Title, body.Description, body.SourceBranch, body.TargetBranch, body.Draft) if !s.apiOK(w, r, err) { return } remove, squash, message := true, false, "" if body.Remove != nil { remove = *body.Remove } if body.Squash != nil { squash = *body.Squash } if body.Message != nil { message = *body.Message } if err := s.Store.SetMergeOptions(r.Context(), mr.ID, remove, squash, message); !s.apiOK(w, r, err) { return } mr, err = s.Store.MergeRequestByNumber(r.Context(), repo.ID, mr.Number) if !s.apiOK(w, r, err) { return } writeJSON(w, http.StatusCreated, s.mrJSON(repo, mr)) return } list, err := s.Store.ListMergeRequests(r.Context(), repo.ID) if !s.apiOK(w, r, err) { return } page, per := pageQuery(r) rows := make([]map[string]any, 0, len(list)) for _, mr := range list { rows = append(rows, s.mrJSON(repo, mr)) } writePage(w, r, slicePage(rows, page, per), len(rows), page, per) } func (s *Server) apiMR(w http.ResponseWriter, r *http.Request) { repo, _, ok := s.apiRepo(w, r, access.RoleReadonly) if !ok { return } n, err := strconv.ParseInt(r.PathValue("number"), 10, 64) if err != nil { s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound"))) return } if r.Method == http.MethodPut { var body struct { Title string `json:"title"` Description string `json:"description"` Labels string `json:"labels"` Remove *bool `json:"remove_source_branch"` Squash *bool `json:"squash"` Message *string `json:"squash_commit_message"` } if err := readJSON(r, &body); err != nil { s.writeAPIErr(w, r, fail(400, i18n.E("err.json"))) return } mr, err := s.opUpdateMR(r.Context(), apiUser(r), repo, n, body.Title, body.Description, body.Labels) if !s.apiOK(w, r, err) { return } if body.Remove != nil || body.Squash != nil || body.Message != nil { remove, squash, message := mr.RemoveSourceBranch, mr.Squash, mr.SquashMessage if body.Remove != nil { remove = *body.Remove } if body.Squash != nil { squash = *body.Squash } if body.Message != nil { message = *body.Message } if err := s.Store.SetMergeOptions(r.Context(), mr.ID, remove, squash, message); !s.apiOK(w, r, err) { return } mr, err = s.Store.MergeRequestByNumber(r.Context(), repo.ID, mr.Number) if !s.apiOK(w, r, err) { return } } writeJSON(w, http.StatusOK, s.mrJSON(repo, mr)) return } mr, err := s.Store.MergeRequestByNumber(r.Context(), repo.ID, n) if err != nil { s.writeAPIErr(w, r, notFound(err)) return } writeJSON(w, http.StatusOK, s.mrJSON(repo, mr)) } func (s *Server) apiMRNotes(w http.ResponseWriter, r *http.Request) { repo, _, ok := s.apiRepo(w, r, access.RoleReadonly) if !ok { return } n, err := strconv.ParseInt(r.PathValue("number"), 10, 64) if err != nil { s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound"))) return } if r.Method == http.MethodGet { mr, err := s.Store.MergeRequestByNumber(r.Context(), repo.ID, n) if err != nil { s.writeAPIErr(w, r, notFound(err)) return } notes, err := s.Store.ListNotes(r.Context(), mr.ID) if !s.apiOK(w, r, err) { return } rows := make([]map[string]any, 0, len(notes)) for _, note := range notes { rows = append(rows, map[string]any{ "id": note.ID, "body": note.Body, "author": note.Author, "file_path": note.FilePath, "line_start": note.LineStart, "line_end": note.LineEnd, "suggestion": note.Suggestion, "parent_id": note.ParentID, "created_at": rfcTime(note.CreatedAt), }) } page, per := pageQuery(r) writePage(w, r, slicePage(rows, page, per), len(rows), page, per) return } var body struct { Body string `json:"body"` Path string `json:"path"` LineStart int `json:"line_start"` LineEnd int `json:"line_end"` ParentID int64 `json:"parent_id"` } if err := readJSON(r, &body); err != nil { s.writeAPIErr(w, r, fail(400, i18n.E("err.json"))) return } note, err := s.opAddNote(r, apiUser(r), repo, n, body.Body, body.Path, body.LineStart, body.LineEnd, body.ParentID) if !s.apiOK(w, r, err) { return } writeJSON(w, http.StatusCreated, map[string]any{"id": note.ID}) } func (s *Server) apiReview(w http.ResponseWriter, r *http.Request) { repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper) if !ok { return } n, err := strconv.ParseInt(r.PathValue("number"), 10, 64) if err != nil { s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound"))) return } var body struct { Status string `json:"status"` } if err := readJSON(r, &body); err != nil { s.writeAPIErr(w, r, fail(400, i18n.E("err.json"))) return } if !s.apiOK(w, r, s.opReview(r.Context(), apiUser(r), repo, n, body.Status)) { return } writeJSON(w, http.StatusOK, map[string]any{"status": body.Status}) } func (s *Server) apiDismissReview(w http.ResponseWriter, r *http.Request) { repo, _, ok := s.apiRepo(w, r, access.RoleMaintainer) if !ok { return } n, err := strconv.ParseInt(r.PathValue("number"), 10, 64) if err != nil { s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound"))) return } var body struct { UserID int64 `json:"user_id"` } if err := readJSON(r, &body); err != nil { s.writeAPIErr(w, r, fail(400, i18n.E("err.json"))) return } if !s.apiOK(w, r, s.opDismissReview(r.Context(), apiUser(r), repo, n, body.UserID)) { return } writeJSON(w, http.StatusOK, map[string]any{"status": "dismissed"}) } func (s *Server) apiSuggestions(w http.ResponseWriter, r *http.Request) { repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper) if !ok { return } n, err := strconv.ParseInt(r.PathValue("number"), 10, 64) if err != nil { s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound"))) return } var body struct { Title string `json:"title"` Description string `json:"description"` IDs []int64 `json:"ids"` } if err := readJSON(r, &body); err != nil { s.writeAPIErr(w, r, fail(400, i18n.E("err.json"))) return } if !s.apiOK(w, r, s.opApplySuggestions(r.Context(), apiUser(r), repo, n, body.Title, body.Description, body.IDs)) { return } writeJSON(w, http.StatusOK, map[string]any{"applied": len(body.IDs)}) } func (s *Server) apiMerge(w http.ResponseWriter, r *http.Request) { repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper) if !ok { return } n, err := strconv.ParseInt(r.PathValue("number"), 10, 64) if err != nil { s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound"))) return } var body struct { Remove *bool `json:"remove_source_branch"` Squash *bool `json:"squash"` Message *string `json:"squash_commit_message"` } if err := readJSON(r, &body); err != nil { s.writeAPIErr(w, r, fail(400, i18n.E("err.json"))) return } out, err := s.opMergeMR(r, apiUser(r), repo, n, mergeChoice{Remove: body.Remove, Squash: body.Squash, Message: body.Message}) if !s.apiOK(w, r, err) { return } writeJSON(w, http.StatusOK, map[string]any{ "state": "merged", "source_branch_removed": out.Removed, "source_branch_skip": out.Skip, "web_url": s.pageURL(repo, "/-/merge-requests/"+strconv.FormatInt(n, 10)), }) } func (s *Server) apiCloseMR(w http.ResponseWriter, r *http.Request) { s.apiSetMR(w, r, false) } func (s *Server) apiReopenMR(w http.ResponseWriter, r *http.Request) { s.apiSetMR(w, r, true) } func (s *Server) apiSetMR(w http.ResponseWriter, r *http.Request, reopen bool) { repo, _, ok := s.apiRepo(w, r, access.RoleReadonly) if !ok { return } n, err := strconv.ParseInt(r.PathValue("number"), 10, 64) if err != nil { s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound"))) return } if !s.apiOK(w, r, s.opCloseMR(r.Context(), apiUser(r), repo, n, reopen)) { return } state := "closed" if reopen { state = "open" } writeJSON(w, http.StatusOK, map[string]any{ "state": state, "web_url": s.pageURL(repo, "/-/merge-requests/"+strconv.FormatInt(n, 10)), }) } func (s *Server) pipeJSON(repo store.Repo, p store.Pipeline) map[string]any { return map[string]any{ "id": p.ID, "sha": p.CommitSHA, "ref": p.Ref, "status": p.Status, "source": p.Source, "actor": p.Actor, "created_at": rfcTime(p.CreatedAt), "started_at": rfcTime(p.StartedAt), "finished_at": rfcTime(p.FinishedAt), "web_url": s.pageURL(repo, "/-/pipelines/"+strconv.FormatInt(p.ID, 10)), } } func jobJSON(j store.Job) map[string]any { return map[string]any{ "id": j.ID, "name": j.Name, "stage": j.Stage, "status": j.Status, "when": j.When, "allow_failure": j.AllowFailure, "started_at": rfcTime(j.StartedAt), "finished_at": rfcTime(j.FinishedAt), } } func (s *Server) apiPipelines(w http.ResponseWriter, r *http.Request) { repo, _, ok := s.apiRepo(w, r, access.RoleReadonly) if !ok { return } if r.Method == http.MethodPost { var body struct { Ref string `json:"ref"` } if err := readJSON(r, &body); err != nil { s.writeAPIErr(w, r, fail(400, i18n.E("err.json"))) return } id, err := s.opRunPipeline(r.Context(), apiUser(r), repo, body.Ref, "api") if !s.apiOK(w, r, err) { return } if p, err := s.Store.PipelineByID(r.Context(), repo.ID, id); err == nil { writeJSON(w, http.StatusCreated, s.pipeJSON(repo, p)) return } writeJSON(w, http.StatusCreated, map[string]any{ "id": id, "web_url": s.pageURL(repo, "/-/pipelines/"+strconv.FormatInt(id, 10)), }) return } list, err := s.Store.ListPipelines(r.Context(), repo.ID) if !s.apiOK(w, r, err) { return } page, per := pageQuery(r) rows := make([]map[string]any, 0, len(list)) for _, p := range list { rows = append(rows, s.pipeJSON(repo, p)) } writePage(w, r, slicePage(rows, page, per), len(rows), page, per) } func (s *Server) apiPipeline(w http.ResponseWriter, r *http.Request) { repo, _, ok := s.apiRepo(w, r, access.RoleReadonly) if !ok { return } id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) if err != nil { s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound"))) return } p, err := s.Store.PipelineByID(r.Context(), repo.ID, id) if err != nil { s.writeAPIErr(w, r, notFound(err)) return } writeJSON(w, http.StatusOK, s.pipeJSON(repo, p)) } func (s *Server) apiRetryPipeline(w http.ResponseWriter, r *http.Request) { repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper) if !ok { return } pipeID, err := strconv.ParseInt(r.PathValue("id"), 10, 64) if err != nil { s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound"))) return } var body struct { Mode string `json:"mode"` } if err := readJSON(r, &body); err != nil { s.writeAPIErr(w, r, fail(400, i18n.E("err.json"))) return } id, err := s.opRetryPipeline(r.Context(), apiUser(r), repo, pipeID, body.Mode) if !s.apiOK(w, r, err) { return } p, err := s.Store.PipelineByID(r.Context(), repo.ID, id) if err != nil { s.writeAPIErr(w, r, notFound(err)) return } code := http.StatusOK if body.Mode == "all" { code = http.StatusCreated } writeJSON(w, code, s.pipeJSON(repo, p)) } func (s *Server) apiCancelPipeline(w http.ResponseWriter, r *http.Request) { repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper) if !ok { return } id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) if err != nil { s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound"))) return } if !s.apiOK(w, r, s.opCancelPipeline(r.Context(), apiUser(r), repo, id)) { return } if p, err := s.Store.PipelineByID(r.Context(), repo.ID, id); err == nil { writeJSON(w, http.StatusOK, s.pipeJSON(repo, p)) return } writeJSON(w, http.StatusOK, map[string]any{ "id": id, "status": "canceled", "web_url": s.pageURL(repo, "/-/pipelines/"+strconv.FormatInt(id, 10)), }) } func (s *Server) apiJobs(w http.ResponseWriter, r *http.Request) { repo, _, ok := s.apiRepo(w, r, access.RoleReadonly) if !ok { return } id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) if err != nil { s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound"))) return } p, err := s.Store.PipelineByID(r.Context(), repo.ID, id) if err != nil { s.writeAPIErr(w, r, notFound(err)) return } jobs, err := s.Store.JobsByPipeline(r.Context(), p.ID) if !s.apiOK(w, r, err) { return } rows := make([]map[string]any, 0, len(jobs)) for _, j := range jobs { rows = append(rows, jobJSON(j)) } writeJSON(w, http.StatusOK, rows) } func (s *Server) apiJob(w http.ResponseWriter, r *http.Request) { _, job, ok := s.apiFindJob(w, r) if !ok { return } writeJSON(w, http.StatusOK, jobJSON(job)) } func (s *Server) apiJobLog(w http.ResponseWriter, r *http.Request) { _, job, ok := s.apiFindJob(w, r) if !ok { return } w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.WriteHeader(http.StatusOK) _, _ = w.Write([]byte(job.Log)) } func (s *Server) apiJobAction(w http.ResponseWriter, r *http.Request, action string) { repo, p, job, ok := s.apiFindJobFull(w, r, access.RoleDeveloper) if !ok { return } updated, err := s.opJobAction(r.Context(), apiUser(r), repo, p.ID, job.ID, action) if !s.apiOK(w, r, err) { return } writeJSON(w, http.StatusOK, jobJSON(updated)) } func (s *Server) apiPlayJob(w http.ResponseWriter, r *http.Request) { s.apiJobAction(w, r, "play") } func (s *Server) apiRetryJob(w http.ResponseWriter, r *http.Request) { s.apiJobAction(w, r, "retry") } func (s *Server) apiCancelJob(w http.ResponseWriter, r *http.Request) { s.apiJobAction(w, r, "cancel") } func (s *Server) apiFindJob(w http.ResponseWriter, r *http.Request) (store.Pipeline, store.Job, bool) { _, p, job, ok := s.apiFindJobFull(w, r, access.RoleReadonly) return p, job, ok } func (s *Server) apiFindJobFull(w http.ResponseWriter, r *http.Request, min access.Role) (store.Repo, store.Pipeline, store.Job, bool) { repo, _, ok := s.apiRepo(w, r, min) if !ok { return store.Repo{}, store.Pipeline{}, store.Job{}, false } pid, err := strconv.ParseInt(r.PathValue("id"), 10, 64) if err != nil { s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound"))) return store.Repo{}, store.Pipeline{}, store.Job{}, false } jid, err := strconv.ParseInt(r.PathValue("job"), 10, 64) if err != nil { s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound"))) return store.Repo{}, store.Pipeline{}, store.Job{}, false } p, err := s.Store.PipelineByID(r.Context(), repo.ID, pid) if err != nil { s.writeAPIErr(w, r, notFound(err)) return store.Repo{}, store.Pipeline{}, store.Job{}, false } jobs, _ := s.Store.JobsByPipeline(r.Context(), p.ID) for _, j := range jobs { if j.ID == jid { return repo, p, j, true } } s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound"))) return store.Repo{}, store.Pipeline{}, store.Job{}, false } func (s *Server) apiArtifacts(w http.ResponseWriter, r *http.Request) { _, job, ok := s.apiFindJob(w, r) if !ok { return } list, err := s.Store.ListArtifacts(r.Context(), job.ID) if !s.apiOK(w, r, err) { return } rows := make([]map[string]any, 0, len(list)) for _, a := range list { rows = append(rows, map[string]any{"path": a.Path, "size": a.Size}) } writeJSON(w, http.StatusOK, rows) } func (s *Server) apiArtifact(w http.ResponseWriter, r *http.Request) { _, job, ok := s.apiFindJob(w, r) if !ok { return } want := r.PathValue("path") if strings.Contains(want, "..") { s.writeAPIErr(w, r, fail(400, i18n.E("err.sugFile"))) return } list, err := s.Store.ListArtifacts(r.Context(), job.ID) if !s.apiOK(w, r, err) { return } for _, a := range list { if a.Path == want { http.ServeFile(w, r, a.StoragePath) return } } s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound"))) } func (s *Server) apiCIFile(w http.ResponseWriter, r *http.Request) { repo, _, ok := s.apiRepo(w, r, access.RoleReadonly) if !ok { return } if r.Method == http.MethodPut { var body struct { Branch string `json:"branch"` Base string `json:"base"` Message string `json:"message"` Content string `json:"content"` OpenMR bool `json:"open_mr"` } if err := readJSON(r, &body); err != nil { s.writeAPIErr(w, r, fail(400, i18n.E("err.json"))) return } sha, number, err := s.opSaveCI(r.Context(), apiUser(r), repo, body.Base, body.Branch, body.Message, body.Content, body.OpenMR) if !s.apiOK(w, r, err) { return } writeJSON(w, http.StatusOK, map[string]any{"id": sha, "merge_request": number}) return } body, err := s.opCIFile(r.Context(), repo, r.URL.Query().Get("ref")) if !s.apiOK(w, r, err) { return } w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.WriteHeader(http.StatusOK) _, _ = w.Write([]byte(body)) } func (s *Server) apiLintCI(w http.ResponseWriter, r *http.Request) { repo, _, ok := s.apiRepo(w, r, access.RoleReadonly) if !ok { return } var body struct { Body string `json:"body"` Ref string `json:"ref"` } if err := readJSON(r, &body); err != nil { s.writeAPIErr(w, r, fail(400, i18n.E("err.json"))) return } out, err := s.opLintCI(r, repo, body.Body, body.Ref) if !s.apiOK(w, r, err) { return } writeJSON(w, http.StatusOK, out) } func (s *Server) apiPresets(w http.ResponseWriter, r *http.Request) { set, err := images.Effective(s.Cfg.CI.ImageOverrides()) if err != nil { s.writeAPIErr(w, r, fail(500, err)) return } rows := make([]map[string]any, 0, len(set)) for _, p := range set { rows = append(rows, map[string]any{"name": "bluegit/" + p.Name, "from": p.From, "runtime": p.Runtime, "tools": p.Tools, "direct": p.Direct}) } writeJSON(w, http.StatusOK, rows) } func (s *Server) apiReleases(w http.ResponseWriter, r *http.Request) { repo, _, ok := s.apiRepo(w, r, access.RoleReadonly) if !ok { return } list, err := s.Store.ListReleases(r.Context(), repo.ID) if !s.apiOK(w, r, err) { return } page, per := pageQuery(r) rows := make([]map[string]any, 0, len(list)) for _, rel := range list { assets := make([]map[string]any, 0, len(rel.Assets)) for _, a := range rel.Assets { assets = append(assets, map[string]any{"name": a.Name, "size": a.Size}) } rows = append(rows, map[string]any{ "id": rel.ID, "tag": rel.Tag, "commit": rel.CommitSHA, "name": rel.Name, "body": rel.Body, "created_at": rfcTime(rel.CreatedAt), "assets": assets, }) } writePage(w, r, slicePage(rows, page, per), len(rows), page, per) } func (s *Server) apiReleaseAsset(w http.ResponseWriter, r *http.Request) { repo, _, ok := s.apiRepo(w, r, access.RoleReadonly) if !ok { return } rel, err := s.Store.ReleaseByTag(r.Context(), repo.ID, r.PathValue("tag")) if err != nil { s.writeAPIErr(w, r, notFound(err)) return } name := r.PathValue("name") for _, a := range rel.Assets { if a.Name == name { w.Header().Set("Content-Disposition", "attachment; filename=\""+strings.ReplaceAll(name, "\"", "")+"\"") http.ServeFile(w, r, a.StoragePath) return } } s.writeAPIErr(w, r, fail(404, i18n.E("err.notFound"))) }