internal/httpd/badge.go

545ba0bcdea3b534903bd78c918c0c025a97eda7
gitbay/internal/httpd/badge.go

119 lines · 3536 bytes

7 symbols in this file
  1package httpd
  2
  3import (
  4	"fmt"
  5	"html/template"
  6	"net/http"
  7	"strings"
  8)
  9
 10// Status badges. A badge is a small SVG served for public repositories,
 11// so a README on any host can show whether the latest build passed.
 12// Private repositories 404 like everywhere else — a badge must not leak
 13// that a repo exists, let alone its state.
 14
 15// badgeColors are the shield fills per build state.
 16var badgeColors = map[string]string{
 17	"success":   "#2da44e",
 18	"failure":   "#cf222e",
 19	"running":   "#bf8700",
 20	"pending":   "#bf8700",
 21	"cancelled": "#6b7280",
 22	"unknown":   "#6b7280",
 23}
 24
 25// badgeWidth approximates Verdana 11px advance so the pill fits its text
 26// without shipping a font metric table.
 27func badgeWidth(s string) int {
 28	w := 0
 29	for _, r := range s {
 30		switch {
 31		case strings.ContainsRune("iljtIJ1.,:;'", r):
 32			w += 4
 33		case strings.ContainsRune("mwMW", r):
 34			w += 10
 35		case r >= 'A' && r <= 'Z':
 36			w += 8
 37		default:
 38			w += 7
 39		}
 40	}
 41	return w + 10
 42}
 43
 44// badgeSVG renders a two-part pill: a grey label and a coloured state.
 45func badgeSVG(label, state string) string {
 46	color := badgeColors[state]
 47	if color == "" {
 48		color = badgeColors["unknown"]
 49	}
 50	lw, sw := badgeWidth(label), badgeWidth(state)
 51	total := lw + sw
 52	label, state = template.HTMLEscapeString(label), template.HTMLEscapeString(state)
 53	return fmt.Sprintf(`<svg xmlns="http://www.w3.org/2000/svg" width="%d" height="20" role="img" aria-label="%s: %s">
 54<title>%s: %s</title>
 55<rect width="%d" height="20" rx="3" fill="#444d56"/>
 56<rect x="%d" width="%d" height="20" rx="3" fill="%s"/>
 57<rect x="%d" width="4" height="20" fill="%s"/>
 58<g fill="#fff" text-anchor="middle" font-family="Verdana,DejaVu Sans,sans-serif" font-size="11">
 59<text x="%d" y="14">%s</text>
 60<text x="%d" y="14">%s</text>
 61</g>
 62</svg>`, total, label, state, label, state,
 63		total, lw, sw, color, lw, color, lw/2, label, lw+sw/2, state)
 64}
 65
 66// buildBadge answers GET /{owner}/{repo}/badge/build.svg[?job=name].
 67func (s *Server) buildBadge(w http.ResponseWriter, r *http.Request) {
 68	label, state, ok := s.badgeState(r)
 69	if !ok {
 70		http.NotFound(w, r)
 71		return
 72	}
 73	badgeHeaders(w, "image/svg+xml; charset=utf-8")
 74	fmt.Fprint(w, badgeSVG(label, state))
 75}
 76
 77// buildBadgePNG answers GET /{owner}/{repo}/badge/build.png[?job=name], for
 78// readers that cannot decode SVG.
 79func (s *Server) buildBadgePNG(w http.ResponseWriter, r *http.Request) {
 80	label, state, ok := s.badgeState(r)
 81	if !ok {
 82		http.NotFound(w, r)
 83		return
 84	}
 85	out, err := badgePNG(label, state)
 86	if err != nil {
 87		http.Error(w, "badge unavailable", http.StatusInternalServerError)
 88		return
 89	}
 90	badgeHeaders(w, "image/png")
 91	w.Write(out)
 92}
 93
 94// badgeState resolves the repo and its latest build. Private repositories
 95// report not ok — a badge must not leak that a repo exists.
 96func (s *Server) badgeState(r *http.Request) (label, state string, ok bool) {
 97	repo, ok := s.publicRepo(r.PathValue("owner"), strings.TrimSuffix(r.PathValue("repo"), ".git"))
 98	if !ok {
 99		return "", "", false
100	}
101	job := r.URL.Query().Get("job")
102	label = "build"
103	if job != "" {
104		label = job
105	}
106	state = "unknown"
107	if b, err := s.st.LatestBuild(repo.ID, job); err == nil {
108		state = b.Status
109	}
110	return label, state, true
111}
112
113func badgeHeaders(w http.ResponseWriter, contentType string) {
114	w.Header().Set("Content-Type", contentType)
115	// Badges are read by other people's caches; keep them briefly fresh
116	// rather than pinned to a stale result.
117	w.Header().Set("Cache-Control", "max-age=60, must-revalidate")
118	w.Header().Set("X-Content-Type-Options", "nosniff")
119}