Skip to content
quarry Artifact [0816bbbda2]
Login

Artifact [0816bbbda2]

Artifact 0816bbbda2b8a7d4e01caf00ac36634093c4c3c2fe4af2128981a16fbb10c8fe:


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
  --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), 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"`
	// 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"`
	Logs  []statusLog `json:"logs,omitempty"`
}

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):
			return v.refuse(1, "refused", show(err.Error()), false, nil)
		}
		return v.refuse(1, "unreachable", "the forge could not be reached: "+show(err.Error()), false, nil)
	}
	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
	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
		}
		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"`
			} `json:"landing"`
			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"`
		}
		if err := e.getJSON(ctx, base, rec.Token, "/r/"+repo+"/landing/"+url.PathEscape(l.ID), nil, &got); err != nil {
			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.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 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 open 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" {
			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.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))
			}
		}
		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()
}