internal/control/status.go

32a5f76e5b270097b63a5bba9a43557cf50ad63d
gitbay/internal/control/status.go history · blame · raw

148 lines · 4613 bytes

  1package control
  2
  3import (
  4	"fmt"
  5	"io"
  6	"strings"
  7
  8	"gitbay.org/gitbay/internal/gitutil"
  9	"gitbay.org/gitbay/internal/policy"
 10	"gitbay.org/gitbay/internal/protocol"
 11	"gitbay.org/gitbay/internal/store"
 12)
 13
 14func init() {
 15	register(Command{Path: []string{"status", "set"},
 16		Summary: "report a commit status (CI)",
 17		Usage:   "status set <owner/name> <sha> --context <c> --state pending|success|failure|error [--description <d>] [--url <u>]",
 18		Flags: []Flag{
 19			{"--context", "<c>", "the check this status reports for", ""},
 20			{"--state", "pending|success|failure|error", "the check's outcome", ""},
 21			{"--description", "<d>", "short text shown beside the state", ""},
 22			{"--url", "<u>", "link to the check's own output", ""},
 23		},
 24		Examples: []string{
 25			"status set krz/gitbay a1b2c3d --context ci/build --state success",
 26		},
 27		Run: runStatusSet})
 28	register(Command{Path: []string{"status", "list"},
 29		Summary:  "statuses on a commit",
 30		Usage:    "status list <owner/name> <sha>",
 31		Examples: []string{"status list krz/gitbay a1b2c3d"},
 32		ReadOnly: true, Run: runStatusList})
 33}
 34
 35var validStatusState = map[string]bool{"pending": true, "success": true, "failure": true, "error": true}
 36
 37func runStatusSet(c *Ctx, args []string) int {
 38	var path, sha, context, state, description, url string
 39	rest := args
 40	for i := 0; i < len(rest); i++ {
 41		switch rest[i] {
 42		case "--context", "--state", "--description", "--url":
 43			if i+1 >= len(rest) {
 44				return c.fail(protocol.ExitUsage, "%s requires a value", rest[i])
 45			}
 46			v := rest[i+1]
 47			switch rest[i] {
 48			case "--context":
 49				context = v
 50			case "--state":
 51				state = v
 52			case "--description":
 53				description = v
 54			case "--url":
 55				url = v
 56			}
 57			i++
 58		default:
 59			if path == "" {
 60				path = rest[i]
 61			} else if sha == "" {
 62				sha = rest[i]
 63			} else {
 64				return c.fail(protocol.ExitUsage, "unexpected argument %q", rest[i])
 65			}
 66		}
 67	}
 68	if path == "" || sha == "" || context == "" || !validStatusState[state] {
 69		return c.usage()
 70	}
 71	if url != "" && !strings.HasPrefix(url, "https://") && !strings.HasPrefix(url, "http://") {
 72		return c.fail(protocol.ExitUsage, "--url must be http(s)")
 73	}
 74	// Reporting a status is a write: CI identities need write access (an
 75	// API token with full scope, or an account grant).
 76	repo, code := resolveRepo(c, path, policy.CanWrite)
 77	if code >= 0 {
 78		return code
 79	}
 80	if code := refuseArchived(c, repo); code >= 0 {
 81		return code
 82	}
 83	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
 84	full, err := gitutil.ResolveRef(dir, sha)
 85	if err != nil {
 86		return c.fail(protocol.ExitNotFound, "no commit %s in %s", sha, repo.Path())
 87	}
 88	if err := c.Store.SetCommitStatus(repo.ID, full, context, state, description, url, c.User.ID); err != nil {
 89		return c.fail(protocol.ExitFailure, "%v", err)
 90	}
 91	c.Store.RecordEvent(repo.ID, c.User.ID, "status",
 92		fmt.Sprintf(`{"sha":%q,"context":%q,"state":%q}`, full, context, state))
 93	return c.emit(map[string]string{"sha": full, "context": context, "state": state}, func(w io.Writer) {
 94		fmt.Fprintf(w, "%s on %.10s: %s\n", context, full, state)
 95	})
 96}
 97
 98func runStatusList(c *Ctx, args []string) int {
 99	if len(args) != 2 {
100		return c.usage()
101	}
102	repo, code := resolveRepo(c, args[0], policy.CanRead)
103	if code >= 0 {
104		return code
105	}
106	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
107	full, err := gitutil.ResolveRef(dir, args[1])
108	if err != nil {
109		return c.fail(protocol.ExitNotFound, "no commit %s in %s", args[1], repo.Path())
110	}
111	statuses, err := c.Store.ListCommitStatuses(repo.ID, full)
112	if err != nil {
113		return c.fail(protocol.ExitFailure, "%v", err)
114	}
115	type out struct {
116		Context     string `json:"context"`
117		State       string `json:"state"`
118		Description string `json:"description,omitempty"`
119		URL         string `json:"url,omitempty"`
120		Creator     string `json:"creator,omitempty"`
121	}
122	var ds []out
123	for _, s := range statuses {
124		ds = append(ds, out{s.Context, s.State, s.Description, s.TargetURL, s.Creator})
125	}
126	d := struct {
127		SHA      string `json:"sha"`
128		Combined string `json:"combined"`
129		Statuses []out  `json:"statuses"`
130	}{full, combinedOf(statuses), ds}
131	return c.emit(d, func(w io.Writer) {
132		tb := c.table(w, "CONTEXT", "STATE", "DESCRIPTION")
133		tb.row(cText("combined"), cState(orNone(d.Combined)), cText(fmt.Sprintf("%.10s", d.SHA)))
134		for _, x := range ds {
135			tb.row(cText(x.Context), cState(x.State), cFlex(x.Description))
136		}
137		tb.flush()
138	})
139}
140
141func combinedOf(statuses []store.CommitStatus) string { return store.CombinedStatus(statuses) }
142
143func orNone(s string) string {
144	if s == "" {
145		return "no statuses"
146	}
147	return s
148}