package server
import (
"encoding/json"
"html/template"
"net/http"
"net/url"
"os"
"os/exec"
"strconv"
"strings"
"gitlab.com/Timfa/bluegit/internal/access"
"gitlab.com/Timfa/bluegit/internal/ci"
"gitlab.com/Timfa/bluegit/internal/gitrepo"
"gitlab.com/Timfa/bluegit/internal/highlight"
"gitlab.com/Timfa/bluegit/internal/store"
)
const ciFile = "blue-ci-cd.yml"
const ciMaxBytes = 200_000
// ciTemplate is het startbestand als blue-ci-cd.yml nog niet bestaat.
// Alles staat in commentaar, zodat opslaan geen job en geen mislukte pipeline maakt.
const ciTemplate = `# blue-ci-cd.yml
# Uncomment the job to run it.
#
# stages:
# - test
#
# unit:
# stage: test
# image: alpine:3.20
# script:
# - echo hello
`
// CIEditor is de Pipeline Editor voor blue-ci-cd.yml.
type CIEditor struct {
Ref string
Body string
Rows []EditorLine
Issues []LintRow
Errors int
Warnings int
Status string
Class string
Missing bool
NeedsMR bool
Suggest string
}
// EditorLine is één gekleurde regel, met een markering als de linter daar klaagt.
type EditorLine struct {
N int
HTML template.HTML
Bad bool
}
// LintRow is één melding onder de editor.
type LintRow struct {
Line int `json:"line"`
Text string `json:"text"`
Warning bool `json:"warning"`
}
func (s *Server) ciEditor(w http.ResponseWriter, r *http.Request) {
_, repo, role, ok := s.guard(w, r, access.RoleReadonly)
if !ok {
return
}
ref := strings.TrimSpace(r.URL.Query().Get("ref"))
if ref == "" {
ref = r.URL.Query().Get("rev")
}
ref = safeRev(ref, repo.DefaultBranch)
v := s.repoView(w, r, repo, role, "edit.title")
v.Wide = true
v.Page = "editor"
v.Rev = ref
dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
s.branchList(r, &v, dir)
body, missing := s.ciFileAt(r, dir, ref)
if missing {
body = ciTemplate
}
model := s.ciEditorModel(r, body, s.includeFrom(r, dir, ref))
model.Ref = ref
model.Missing = missing
patterns, _ := s.Store.ProtectedPatterns(r.Context(), repo.ID)
model.NeedsMR = access.BranchProtected(patterns, ref) && !role.CanPushBranch(true)
if model.NeedsMR {
model.Suggest = s.suggestCIBranch(r, dir, patterns)
}
v.Editor = model
s.render(w, "editor", v)
}
func (s *Server) lintCI(w http.ResponseWriter, r *http.Request) {
_, repo, _, ok := s.guard(w, r, access.RoleReadonly)
if !ok || !s.csrfOK(w, r) {
return
}
body := r.FormValue("body")
if len(body) > ciMaxBytes {
http.Error(w, s.tr(r, "edit.fail"), http.StatusBadRequest)
return
}
ref := safeRev(r.FormValue("ref"), repo.DefaultBranch)
dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
model := s.ciEditorModel(r, body, s.includeFrom(r, dir, ref))
lines := make([]string, len(model.Rows))
var bad []int
for i, row := range model.Rows {
lines[i] = string(row.HTML)
if row.Bad {
bad = append(bad, row.N)
}
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"status": model.Status,
"statusClass": model.Class,
"errors": model.Errors,
"warnings": model.Warnings,
"issues": model.Issues,
"lines": lines,
"bad": bad,
})
}
func (s *Server) saveCIEditor(w http.ResponseWriter, r *http.Request) {
u, repo, role, ok := s.guard(w, r, access.RoleDeveloper)
if !ok || !s.csrfOK(w, r) {
return
}
base := safeRev(r.FormValue("base"), repo.DefaultBranch)
branch := strings.TrimSpace(r.FormValue("branch"))
if !validBranchName(branch) {
s.redirect(w, r, repoURL(repo)+"/-/ci/editor?ref="+url.QueryEscape(base), "", s.tr(r, "edit.badBranch"))
return
}
back := repoURL(repo) + "/-/ci/editor?ref=" + url.QueryEscape(branch)
message := strings.TrimSpace(r.FormValue("message"))
if message == "" {
s.redirect(w, r, back, "", s.tr(r, "edit.needMessage"))
return
}
body := r.FormValue("body")
if len(body) > ciMaxBytes {
s.redirect(w, r, back, "", s.tr(r, "edit.fail"))
return
}
openMR := r.FormValue("open_mr") == "1"
patterns, _ := s.Store.ProtectedPatterns(r.Context(), repo.ID)
if openMR && (branch == base || access.BranchProtected(patterns, branch)) {
s.redirect(w, r, back, "", s.tr(r, "edit.badBranch"))
return
}
if access.BranchProtected(patterns, branch) && !role.CanPushBranch(true) {
s.redirect(w, r, back, "", s.tr(r, "edit.protected"))
return
}
dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
if err := s.ensureBranch(r, dir, branch, base); err != nil {
s.redirect(w, r, back, "", s.tr(r, "edit.fail"))
return
}
work, err := os.MkdirTemp("", "bluegit-edit-")
if err != nil {
s.redirect(w, r, back, "", s.tr(r, "edit.fail"))
return
}
defer os.RemoveAll(work)
email := u.Username + "@users.git.timfalken.com"
err = gitrepo.CommitOnBranch(r.Context(), s.Git, dir, work, branch, u.Username, email, message, "", map[string]string{ciFile: body}, role, patterns)
if err != nil {
low := strings.ToLower(err.Error())
if strings.Contains(low, "nothing to commit") || strings.Contains(low, "nothing added") {
s.redirect(w, r, back, "", s.tr(r, "edit.same"))
return
}
if s.Log != nil {
s.Log.Error("ci-editor", "err", err)
}
s.redirect(w, r, back, "", s.tr(r, "edit.fail"))
return
}
if openMR {
number, mrErr := s.openCIMergeRequest(r, repo, u, dir, branch, base, message)
if mrErr != nil {
if s.Log != nil {
s.Log.Error("ci-editor-mr", "err", mrErr)
}
s.redirect(w, r, back, "", s.tr(r, "edit.fail"))
return
}
s.redirect(w, r, repoURL(repo)+"/-/merge-requests/"+strconv.FormatInt(number, 10), s.tr(r, "flash.mrOpened"), "")
return
}
s.redirect(w, r, back, s.tr(r, "edit.saved"), "")
}
// openCIMergeRequest opent een merge request van branch naar target.
// Een open verzoek met dezelfde bronbranch wordt hergebruikt.
func (s *Server) openCIMergeRequest(r *http.Request, repo store.Repo, author store.User, dir, branch, target, title string) (int64, error) {
existing, err := s.Store.OpenMergeRequestsBySource(r.Context(), repo.ID, branch)
if err != nil {
return 0, err
}
if len(existing) > 0 {
return existing[0].Number, nil
}
mr, err := s.Store.CreateMergeRequest(r.Context(), repo.ID, author.ID, title, "", branch, target)
if err != nil {
return 0, err
}
num := strconv.FormatInt(mr.Number, 10)
if sha := gitOne(r.Context(), s.Git, dir, "rev-parse", "--verify", "refs/heads/"+branch); sha != "" {
s.startOneMergePipeline(r.Context(), repo, sha, author.Username, "", mr)
}
s.Dispatch(repo.ID, pushEvent(repo, "merge_request", target, "", author.Username, s.tr(r, "hook.mr", num, mr.Title), repoURL(repo)+"/-/merge-requests/"+num))
s.recordContribution(author.ID, repo.ID, "merge_request", mrRef(mr.ID), mr.CreatedAt)
return mr.Number, nil
}
func (s *Server) ciEditorModel(r *http.Request, body string, read func(string) ([]byte, error)) *CIEditor {
_, issues := ci.Lint([]byte(body), read)
bad := map[int]bool{}
var rows []LintRow
errors, warnings := 0, 0
for _, is := range issues {
line := is.Line
if line < 1 {
line = 1
}
text := s.tr(r, is.Key, is.Args...)
rows = append(rows, LintRow{Line: line, Text: text, Warning: is.Warning})
if is.Warning {
warnings++
continue
}
errors++
bad[line] = true
}
painted := highlight.Lines(ciFile, body)
if len(painted) == 0 {
painted = []string{""}
}
if strings.HasSuffix(body, "\n") {
painted = append(painted, "")
}
lines := make([]EditorLine, len(painted))
for i, htmlLine := range painted {
n := i + 1
lines[i] = EditorLine{N: n, HTML: template.HTML(htmlLine), Bad: bad[n]}
}
status, class := s.tr(r, "edit.clean"), "passed"
if errors > 0 {
key := "edit.issues"
if errors == 1 {
key = "edit.issueOne"
}
status, class = s.tr(r, key, errors), "failed"
} else if warnings > 0 {
key := "edit.warnings"
if warnings == 1 {
key = "edit.warningOne"
}
status, class = s.tr(r, key, warnings), "warning"
}
if rows == nil {
rows = []LintRow{}
}
return &CIEditor{
Body: body, Rows: lines, Issues: rows,
Errors: errors, Warnings: warnings, Status: status, Class: class,
}
}
func (s *Server) ciFileAt(r *http.Request, dir, ref string) (string, bool) {
out, err := exec.CommandContext(r.Context(), s.Git, "-C", dir, "show", ref+":"+ciFile).Output()
if err != nil {
return "", true
}
if len(out) > ciMaxBytes {
return "", false
}
return string(out), false
}
func (s *Server) suggestCIBranch(r *http.Request, dir string, patterns []string) string {
const base = "add-blue-ci-cd"
for n := 1; n < 100; n++ {
name := base
if n > 1 {
name = base + "-" + strconv.Itoa(n)
}
if access.BranchProtected(patterns, name) {
continue
}
if gitOne(r.Context(), s.Git, dir, "rev-parse", "--verify", "--quiet", "refs/heads/"+name) == "" {
return name
}
}
return base
}
func (s *Server) includeFrom(r *http.Request, dir, ref string) func(string) ([]byte, error) {
return func(path string) ([]byte, error) {
if !validInclude(path) {
return nil, os.ErrInvalid
}
return exec.CommandContext(r.Context(), s.Git, "-C", dir, "show", ref+":"+path).Output()
}
}
func (s *Server) ensureBranch(r *http.Request, dir, branch, base string) error {
if gitOne(r.Context(), s.Git, dir, "rev-parse", "--verify", "--quiet", "refs/heads/"+branch) != "" {
return nil
}
if gitOne(r.Context(), s.Git, dir, "rev-parse", "--verify", "--quiet", "refs/heads/"+base) == "" {
return os.ErrNotExist
}
cmd := exec.CommandContext(r.Context(), s.Git, "-C", dir, "branch", branch, base)
if out, err := cmd.CombinedOutput(); err != nil {
if s.Log != nil {
s.Log.Error("ci-branch", "err", err, "out", string(out))
}
return err
}
return nil
}
func validBranchName(s string) bool {
if s == "" || s == "@" || strings.HasPrefix(s, "-") || strings.HasPrefix(s, "/") || strings.HasSuffix(s, "/") || strings.HasSuffix(s, ".") || strings.Contains(s, "..") || strings.Contains(s, "//") || strings.Contains(s, "@{") {
return false
}
return !strings.ContainsAny(s, " \t\n~^:?*[\\")
}
func validInclude(p string) bool {
if p == "" || strings.HasPrefix(p, "/") || strings.Contains(p, `\`) || strings.Contains(p, "..") {
return false
}
return true
}