package pickupclient
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"time"
"craftdesign.group/quarry/internal/nextstep"
)
// quarry status (RFC 0033 step 8): what is my work waiting on, in this
// checkout's repository. It composes landing.list, landing.get,
// ci.run.log, inbox.list and me.account. Every sentence about a
// landing's state is the forge's (`waiting` and its `next`); the client
// adds only layout.
const statusHelp = `usage: quarry status [!N|BRANCH] [--log] [--json]
What is my work waiting on? In this checkout's repository: your open
landings, each with what it waits on and the one next step the forge
names, then up to five unread inbox rows that are not already settled (this
repository's first). It
never marks anything read.
!N|BRANCH that landing only, whoever opened it; when it is part of a
stack, every rung bottom-up (check state, who armed it, what it
waits on and its next step), then the branch it finally lands on
--log for a landing whose checks failed, the last lines of each
failed step
--json one JSON object on stdout: ok, host, repo, account, landings
(each with its waiting and next, and for a stacked one its
stack and finalTarget), inbox, next
Exit: 0 it answered (whatever the landings wait on), 1 refused, 2 usage,
4 not logged in.
Example:
quarry status
`
const (
statusInboxCap = 5
statusLogTail = 20
)
type statusWaiting struct {
On string `json:"on"`
Say string `json:"say"`
Who string `json:"who"`
Next *nextstep.Next `json:"next"`
}
type statusLanding struct {
Number int `json:"number"`
ID string `json:"id"`
Branch string `json:"branch"`
Target string `json:"target"`
Title string `json:"title"`
State string `json:"state"`
CI string `json:"ci"`
Waiting statusWaiting `json:"waiting"`
// ArmLapsed is why the landing's auto-land arm stopped (a check-in
// pushed after it), as the forge records it; empty when it did not.
// Waiting.Next is then quarry land, which arms the tip now pushed.
ArmLapsed string `json:"armLapsed,omitempty"`
// Facts are the landing's own fields, for a forge that does not say
// what it waits on: values as the forge gave them, none composed.
Facts []string `json:"facts"`
// Updated and SettledBy are set for a landing that is no longer
// open: when it settled, and the reply that settled it.
Updated string `json:"updated,omitempty"`
SettledBy string `json:"settled_by,omitempty"`
// LandedTip is the branch check-in a landed landing merged, and
// LandedOnto the target tip it merged onto.
LandedTip string `json:"landedTip,omitempty"`
LandedOnto string `json:"landedOnto,omitempty"`
Logs []statusLog `json:"logs,omitempty"`
// Stack is every rung of the stack this landing is part of,
// bottom-up, and FinalTarget the branch it lands on; absent for a
// landing on its own. A named selection (!N) carries each rung's
// own reading; the unselected list carries the rungs alone.
Stack []statusRung `json:"stack,omitempty"`
FinalTarget string `json:"finalTarget,omitempty"`
}
// statusRung is one rung of a stack: who armed it, and what it waits on
// with the forge's next step, as that rung's own landing.get says.
type statusRung struct {
Position int `json:"position"`
Number int `json:"number"`
ID string `json:"id"`
Branch string `json:"branch"`
Target string `json:"target"`
State string `json:"state"`
CI string `json:"ci"`
ArmedBy string `json:"armedBy"`
Waiting statusWaiting `json:"waiting"`
// ArmLapsed is why this rung's arm stopped, as statusLanding's.
ArmLapsed string `json:"armLapsed,omitempty"`
}
// relandNext is the next step for a landing whose arm lapsed: quarry
// land pushes and arms for the tip as it now is.
func relandNext(branch string) *nextstep.Next {
cmd := "quarry land"
if branch != "" && strings.Trim(branch, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._/+@-") == "" && !strings.HasPrefix(branch, "-") {
cmd += " " + branch
}
return &nextstep.Next{Say: "The arm lapsed when the branch moved; land it again to arm the tip now pushed.", Cmd: cmd}
}
type statusLog struct {
Check string `json:"check"`
RunID string `json:"runId"`
Step string `json:"step"`
Text string `json:"text"`
}
type statusRow struct {
ID string `json:"id"`
Reason string `json:"reason"`
Repo string `json:"repo"`
From string `json:"from"`
Summary string `json:"summary"`
Link string `json:"link"`
At string `json:"at"`
}
type statusInbox struct {
Unread int `json:"unread"`
Rows []statusRow `json:"rows"`
}
type statusJSON struct {
OK bool `json:"ok"`
Host string `json:"host"`
Repo string `json:"repo"`
Address string `json:"address"`
Account string `json:"account"`
Landings []statusLanding `json:"landings"`
Inbox statusInbox `json:"inbox"`
Next *nextstep.Next `json:"next"`
}
// getJSON reads one forge route with the token. A non-200 is a
// statusError; a 401 is errTokenDead.
func (e *Env) getJSON(ctx context.Context, base *url.URL, token, path string, q url.Values, into any) error {
u, err := apiTarget(base, apiPrefix+path)
if err != nil {
return err
}
u.RawQuery = q.Encode()
req, err := http.NewRequestWithContext(ctx, "GET", u.String(), nil)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Accept", "application/json")
resp, err := e.Client.Do(req)
if err != nil {
var ue *url.Error
if errors.As(err, &ue) {
err = ue.Err
}
return err
}
defer resp.Body.Close()
switch {
case resp.StatusCode == http.StatusUnauthorized:
return errTokenDead
case resp.StatusCode != http.StatusOK:
return statusError(resp.StatusCode)
}
if err := json.NewDecoder(io.LimitReader(resp.Body, pickupBodyMax)).Decode(into); err != nil {
return errBadAnswer
}
return nil
}
// errBadAnswer is a 200 whose body is not the JSON the route promises.
var errBadAnswer = errors.New("the forge's answer was not readable")
// Status is quarry status.
func Status(ctx context.Context, args []string, e *Env) int {
e.fillLogin()
args, asJSON := stripJSON(args)
v := voice{e, e.named("status"), asJSON, nil}
usage := func() int {
return v.refuse(2, "usage", "usage: quarry status [!N|BRANCH] [--log] [--json] (quarry status --help)", false,
&nextstep.Next{Say: "See quarry status --help.", Cmd: "quarry status --help"})
}
var sel string
var logs bool
for _, a := range args {
switch {
case a == "-h" || a == "--help" || a == "-help":
fmt.Fprint(e.Stdout, statusHelp)
return 0
case a == "--log":
logs = true
case strings.HasPrefix(a, "-") || sel != "":
return usage()
default:
sel = a
}
}
cwd, err := e.Getwd()
if err != nil {
return v.refuse(1, "refused", "this directory cannot be read: "+show(err.Error()), false, nil)
}
var remote *url.URL
if kind, root := checkoutKind(cwd); kind != "" {
remote = e.checkoutRemote(ctx, kind, root)
}
segs, serr := remoteSegments(remote)
if serr != nil {
return v.refuse(1, "no_repo", "this directory is not a checkout of a repository of the forge", false,
&nextstep.Next{Say: "Run this inside a checkout; quarry repo clone O/N makes one.", Cmd: "quarry repo clone O/N"})
}
base, err := e.forgeFor("", remote)
if err != nil {
return v.refuse(2, "usage", show(err.Error()), false, nil)
}
v.base = base
rec, ok := e.token(base)
if !ok {
return v.noLogin(base)
}
fail := func(err error) int {
var se statusError
switch {
case errors.Is(err, errBadAnswer):
return v.refuse(1, "bad_answer", "the forge answered with something this client cannot read", false,
&nextstep.Next{Say: "Check that the forge and this client are the same version.", Cmd: "quarry doctor"})
case errors.Is(err, errNoSuchRepo):
return v.refuse(1, "no_repo", "the forge has no repository "+show(strings.Join(segs, "/")), false,
&nextstep.Next{Say: "Check the checkout's remote."})
case errors.Is(err, errTokenDead):
return v.refuse(exitNoLogin, noLoginCode, "the forge does not take this machine's token", false,
&nextstep.Next{Say: "Log this machine in again.", Cmd: loginCmd, Help: credsHelp})
case errors.As(err, &se) && int(se) == http.StatusServiceUnavailable:
return v.busy(0)
case errors.As(err, &se):
return v.refuse(1, "refused", show(err.Error()), false, nil)
}
return e.netRefuse(ctx, v, base, err, "quarry status")
}
ctx, cancel := context.WithTimeout(ctx, 60*time.Second)
defer cancel()
ref, err := e.resolveRepo(ctx, base, rec.Token, segs, true)
if err != nil {
return fail(err)
}
repo := ref.Key
me, err := e.readMe(ctx, base, rec.Token)
if err != nil {
if se, ok := err.(statusError); ok && (se == 401 || se == 403) {
return fail(errTokenDead)
}
var syn *json.SyntaxError
var typ *json.UnmarshalTypeError
if errors.As(err, &syn) || errors.As(err, &typ) || errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
err = errBadAnswer
}
return fail(err)
}
var list struct {
Landings []struct {
ID string `json:"id"`
Number int `json:"number"`
Branch string `json:"branch"`
Author string `json:"author"`
} `json:"landings"`
}
if err := e.getJSON(ctx, base, rec.Token, "/r/"+repo+"/landing", url.Values{"state": {"open"}, "limit": {"200"}}, &list); err != nil {
if se, ok := err.(statusError); ok && se == 404 {
err = errNoSuchRepo
}
return fail(err)
}
var landings []statusLanding
var ids []string
for _, l := range list.Landings {
switch {
case sel == "" && !strings.EqualFold(l.Author, me.Name):
continue
case sel != "" && sel != "!"+strconv.Itoa(l.Number) && sel != l.Branch:
continue
}
ids = append(ids, l.ID)
}
// A selector that names no open landing may still name one that
// settled: ask the forge for it by number or hash, whatever its state.
direct := false
if sel != "" && len(ids) == 0 {
ids, direct = []string{strings.TrimPrefix(sel, "!")}, true
}
for _, id := range ids {
var got struct {
Landing struct {
ID string `json:"id"`
Number int `json:"number"`
Branch string `json:"branch"`
Target string `json:"target"`
Title string `json:"title"`
State string `json:"state"`
CI string `json:"ci"`
AutoBy string `json:"autoBy"`
// Updated and SettledBy say when a settled landing
// settled and by which reply.
Updated string `json:"updated"`
SettledBy string `json:"settled_by"`
} `json:"landing"`
AutoLapsed string `json:"autoLapsed"`
LandedTip string `json:"landedTip"`
LandedOnto string `json:"landedOnto"`
Mergeable string `json:"mergeable"`
Behind int `json:"behind"`
Unmet []string `json:"unmet"`
Checks []struct {
RunID string `json:"runId"`
Workflow string `json:"workflow"`
Pipeline string `json:"pipeline"`
} `json:"checks"`
Waiting statusWaiting `json:"waiting"`
LandsOn string `json:"landsOn"`
Stack landStrata `json:"stack"`
}
if err := e.getJSON(ctx, base, rec.Token, "/r/"+repo+"/landing/"+url.PathEscape(id), nil, &got); err != nil {
if se, ok := err.(statusError); ok && direct && se == 404 {
break
}
return fail(err)
}
sl := statusLanding{Number: got.Landing.Number, ID: got.Landing.ID, Branch: got.Landing.Branch,
Target: got.Landing.Target, Title: got.Landing.Title, State: got.Landing.State, CI: got.Landing.CI, Waiting: got.Waiting}
sl.Facts = []string{}
if got.AutoLapsed != "" && got.Landing.State == "open" && got.Landing.AutoBy == "" {
sl.ArmLapsed, sl.Waiting.Next = got.AutoLapsed, relandNext(got.Landing.Branch)
}
if got.Landing.State != "" && got.Landing.State != "open" {
// Settled: nothing waits, so the record's own words stand.
sl.Waiting = statusWaiting{}
sl.Updated, sl.SettledBy = got.Landing.Updated, got.Landing.SettledBy
sl.LandedTip, sl.LandedOnto = got.LandedTip, got.LandedOnto
sl.Facts = append(sl.Facts, settledLine(got.Landing.State, got.Landing.Updated, got.LandedTip))
} else if got.Waiting.Say == "" {
add := func(k, val string) {
if val != "" {
sl.Facts = append(sl.Facts, k+" "+val)
}
}
add("state", got.Landing.State)
add("ci", got.Landing.CI)
add("mergeable", got.Mergeable)
add("armed-by", got.Landing.AutoBy)
if got.Behind > 0 {
add("behind", strconv.Itoa(got.Behind))
}
add("unmet", strings.Join(got.Unmet, ", "))
}
if len(got.Stack.Segments) > 1 && got.Landing.State == "open" {
sl.FinalTarget = got.LandsOn
if sl.FinalTarget == "" {
sl.FinalTarget = got.Stack.Segments[0].Target
}
for _, g := range got.Stack.Segments {
r := statusRung{Position: g.Position, Number: g.Number, ID: g.ID, Branch: g.Branch, Target: g.Target, State: g.State, CI: g.CI}
switch {
case g.ID == got.Landing.ID:
r.CI, r.ArmedBy, r.Waiting = got.Landing.CI, got.Landing.AutoBy, got.Waiting
r.ArmLapsed, r.Waiting.Next = sl.ArmLapsed, sl.Waiting.Next
if r.ArmLapsed == "" {
r.Waiting.Next = got.Waiting.Next
}
case sel != "":
// Each other rung says for itself what it waits on.
var rg struct {
Landing struct {
CI string `json:"ci"`
AutoBy string `json:"autoBy"`
} `json:"landing"`
Waiting statusWaiting `json:"waiting"`
AutoLapsed string `json:"autoLapsed"`
}
if err := e.getJSON(ctx, base, rec.Token, "/r/"+repo+"/landing/"+url.PathEscape(g.ID), nil, &rg); err != nil {
return fail(err)
}
if rg.Landing.CI != "" {
r.CI = rg.Landing.CI
}
r.ArmedBy, r.Waiting = rg.Landing.AutoBy, rg.Waiting
if rg.AutoLapsed != "" && rg.Landing.AutoBy == "" && g.State == "open" {
r.ArmLapsed, r.Waiting.Next = rg.AutoLapsed, relandNext(g.Branch)
}
}
sl.Stack = append(sl.Stack, r)
}
}
if logs && got.Landing.CI == "ci-fail" {
for _, c := range got.Checks {
if c.RunID == "" {
continue
}
var lg struct {
Steps []struct {
Step string `json:"step"`
Failed bool `json:"failed"`
Text string `json:"text"`
} `json:"steps"`
}
q := url.Values{"tail": {strconv.Itoa(statusLogTail)}}
if err := e.getJSON(ctx, base, rec.Token, "/r/"+repo+"/ci/runs/"+url.PathEscape(c.RunID)+"/log", q, &lg); err != nil {
return fail(err)
}
name := c.Pipeline
if name == "" {
name = c.Workflow
}
for _, s := range lg.Steps {
if s.Failed {
sl.Logs = append(sl.Logs, statusLog{Check: name, RunID: c.RunID, Step: s.Step, Text: s.Text})
}
}
}
}
landings = append(landings, sl)
}
if sel != "" && len(landings) == 0 {
return v.refuse(1, "no_landing", "no landing "+show(sel)+" in "+repo, false,
&nextstep.Next{Say: "List yours.", Cmd: "quarry status"})
}
var inbox statusInbox
if sel == "" {
var raw struct {
Rows []struct {
statusRow
Read bool `json:"read"`
// Settled is the forge's word that what the row asked
// has happened; a forge without it says nothing, and the
// row is shown as before.
Settled bool `json:"settled"`
} `json:"rows"`
}
if err := e.getJSON(ctx, base, rec.Token, "/me/inbox", url.Values{"limit": {"50"}}, &raw); err != nil {
return fail(err)
}
for _, r := range raw.Rows {
if !r.Read && !r.Settled {
inbox.Rows = append(inbox.Rows, r.statusRow)
}
}
inbox.Unread = len(inbox.Rows)
// The forge's own count is the badge's number, over the whole
// inbox rather than the newest page; a forge without it, or a
// count below the rows in hand, leaves the page's count.
var cnt struct {
Unread *int `json:"unread"`
}
if e.getJSON(ctx, base, rec.Token, "/me/inbox/count", nil, &cnt) == nil && cnt.Unread != nil && *cnt.Unread > inbox.Unread {
inbox.Unread = *cnt.Unread
}
sort.SliceStable(inbox.Rows, func(i, j int) bool {
here := func(r string) bool { return r == repo || r == ref.Address }
return here(inbox.Rows[i].Repo) && !here(inbox.Rows[j].Repo)
})
if len(inbox.Rows) > statusInboxCap {
inbox.Rows = inbox.Rows[:statusInboxCap]
}
}
if inbox.Rows == nil {
inbox.Rows = []statusRow{}
}
if landings == nil {
landings = []statusLanding{}
}
var first *nextstep.Next
for _, l := range landings {
if l.Waiting.Next != nil && (l.Waiting.On != "nothing" || l.ArmLapsed != "") {
first = l.Waiting.Next
break
}
}
if asJSON {
v.print(statusJSON{OK: true, Host: base.Host, Repo: repo, Address: ref.Address, Account: me.Name, Landings: landings, Inbox: inbox, Next: first})
return 0
}
fmt.Fprintf(e.Stdout, "%s on %s, as %s\n", show(ref.Address), base.Host, show(me.Name))
if len(landings) == 0 {
fmt.Fprintln(e.Stdout, " No open landings of yours here.")
}
for _, l := range landings {
name := "!" + strconv.Itoa(l.Number)
if l.Number == 0 {
name = "-"
}
fmt.Fprintf(e.Stdout, " %s %s -> %s\n", show(name), show(l.Branch), show(l.Target))
if l.Waiting.Say != "" {
fmt.Fprintf(e.Stdout, " %s\n", show(l.Waiting.Say))
} else if len(l.Facts) > 0 {
fmt.Fprintf(e.Stdout, " %s\n", show(strings.Join(l.Facts, "; ")))
}
if l.ArmLapsed != "" {
fmt.Fprintf(e.Stdout, " arm lapsed: %s\n", show(l.ArmLapsed))
}
if l.Waiting.Who != "" {
fmt.Fprintf(e.Stdout, " who %s\n", show(l.Waiting.Who))
}
if n := l.Waiting.Next; n != nil {
fmt.Fprintf(e.Stdout, " next %s\n", show(n.Say))
if n.Cmd != "" && !strings.ContainsAny(n.Cmd, "\r\n") {
fmt.Fprintf(e.Stdout, " run %s\n", show(n.Cmd))
}
}
if len(l.Stack) > 0 && sel != "" {
fmt.Fprintln(e.Stdout, " stack, bottom-up:")
for _, r := range l.Stack {
armed := "not armed"
if r.ArmedBy != "" {
armed = "armed by " + r.ArmedBy
}
ci := r.CI
if ci == "" {
ci = "no checks yet"
}
fmt.Fprintf(e.Stdout, " %s %s %s; %s\n", show(rungName(landRung{r.Number, r.Branch})), show(r.Branch), show(ci), show(armed))
if r.Waiting.Say != "" {
fmt.Fprintf(e.Stdout, " %s\n", show(r.Waiting.Say))
}
if r.ArmLapsed != "" {
fmt.Fprintf(e.Stdout, " arm lapsed: %s\n", show(r.ArmLapsed))
}
if n := r.Waiting.Next; n != nil {
fmt.Fprintf(e.Stdout, " next %s\n", show(n.Say))
if n.Cmd != "" && !strings.ContainsAny(n.Cmd, "\r\n") {
fmt.Fprintf(e.Stdout, " run %s\n", show(n.Cmd))
}
}
}
fmt.Fprintf(e.Stdout, " lands on %s\n", show(l.FinalTarget))
}
for _, g := range l.Logs {
fmt.Fprintf(e.Stdout, " check %s, step %s (run %s):\n", show(g.Check), show(g.Step), show(g.RunID))
for _, line := range strings.Split(strings.TrimRight(g.Text, "\n"), "\n") {
fmt.Fprintf(e.Stdout, " %s\n", show(line))
}
}
}
if sel == "" {
if len(inbox.Rows) == 0 {
fmt.Fprintln(e.Stdout, "Nothing waits on you.")
} else {
fmt.Fprintf(e.Stdout, "Waiting on you (%d unread):\n", inbox.Unread)
for _, r := range inbox.Rows {
fmt.Fprintf(e.Stdout, " %s\n", show(r.Summary))
if link := statusLink(base, r.Link); link != "" {
fmt.Fprintf(e.Stdout, " %s\n", show(link))
}
}
if inbox.Unread > len(inbox.Rows) {
fmt.Fprintf(e.Stdout, " and %d more\n", inbox.Unread-len(inbox.Rows))
}
}
}
return 0
}
// statusLink is a row's link as an address of the forge; a link that
// leaves the forge is not printed.
func statusLink(base *url.URL, link string) string {
if link == "" {
return ""
}
u, err := base.Parse(link)
if err != nil || !nextstep.SameOrigin(u, base) {
return ""
}
return u.String()
}
// settledLine says what became of a landing that is no longer open, in
// the record's own state word: when (in UTC, to the minute) and, for one
// that landed, the check-in it merged.
func settledLine(state, at, tip string) string {
line := strings.ToUpper(state[:1]) + state[1:]
if state == "accepted" {
line = "Landed"
}
if t, err := time.Parse("2006-01-02T15:04:05.999999999", at); err == nil {
line += " " + t.Format("2006-01-02 15:04") + " UTC"
} else if t, err := time.Parse(time.RFC3339Nano, at); err == nil {
line += " " + t.UTC().Format("2006-01-02 15:04") + " UTC"
}
if state == "accepted" && len(tip) >= 12 {
line += " as " + tip[:12]
}
return line + "."
}