Skip to content
quarry Artifact [131c83a6e1]
Login

Artifact [131c83a6e1]

Artifact 131c83a6e1e3c904b995eb3884925a175ae0240b96b2a5ff958074682901b591:


package pickupclient

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strings"
	"time"

	"craftdesign.group/quarry/internal/nextstep"
)

const ticketHelp = `usage: quarry ticket show ID [-R OWNER/NAME] [--json]
       quarry ticket list [-R OWNER/NAME] [--status S] [--json]

Read a repository's tickets back from the terminal.

  show ID    one ticket: its fields, then its comments in order with
             author and time. ID is a ticket number or a prefix of its id.
  list       one line per ticket: number, short id, status, type, title.
  -R         the repository, as OWNER/NAME; without it, the repository of
             this checkout's remote
  --status   list only tickets with this status
  --json     the forge's answer, unchanged

Exit: 0 it answered, 1 refused, 2 usage, 4 not logged in.

Example:
  quarry ticket show 497 -R dmestas/quarry
`

type ticketAnswer struct {
	Ticket struct {
		ID      string `json:"id"`
		Created string `json:"created"`
		Updated string `json:"updated"`
		Fields  []struct {
			Name  string `json:"name"`
			Value string `json:"value"`
		} `json:"fields"`
		Description string `json:"description"`
		Comments    []struct {
			Date     string `json:"date"`
			Login    string `json:"login"`
			Username string `json:"username"`
			Body     string `json:"body"`
		} `json:"comments"`
	} `json:"ticket"`
	Number int `json:"number"`
}

type ticketRow struct {
	ID      string `json:"id"`
	Number  int    `json:"number"`
	Status  string `json:"status"`
	Type    string `json:"type"`
	Title   string `json:"title"`
	Updated string `json:"updated"`
}

// Ticket is quarry ticket show|list.
func Ticket(ctx context.Context, args []string, e *Env) int {
	e.fillLogin()
	args, asJSON := stripJSON(args)
	v := voice{e, e.named("ticket"), asJSON, nil}
	usage := func() int {
		return v.refuse(2, "usage", "usage: quarry ticket show ID | list [-R OWNER/NAME] [--status S] [--json] (quarry ticket --help)", false,
			&nextstep.Next{Say: "See quarry ticket --help.", Cmd: "quarry ticket --help"})
	}
	var sub, id, repoArg, status string
	var repoSet bool
	for i := 0; i < len(args); i++ {
		switch a := args[i]; {
		case a == "-h" || a == "--help" || a == "-help":
			fmt.Fprint(e.Stdout, ticketHelp)
			return 0
		case a == "-R" || a == "--repo" || a == "--status":
			if i+1 >= len(args) {
				return usage()
			}
			if a == "--status" {
				status = args[i+1]
			} else {
				repoArg, repoSet = args[i+1], true
			}
			i++
		case strings.HasPrefix(a, "-"):
			return usage()
		case sub == "":
			sub = a
		case sub == "show" && id == "":
			id = a
		default:
			return usage()
		}
	}
	if sub != "show" && sub != "list" || sub == "show" && id == "" || sub == "list" && status != "" && strings.ContainsAny(status, "&=#\r\n") {
		return usage()
	}
	if sub == "show" && strings.ContainsAny(id, "/?#") {
		return usage()
	}

	var remote *url.URL
	var segs []string
	if repoSet {
		if repoArg == "" {
			return usage()
		}
		segs = strings.Split(repoArg, "/")
		if len(segs) > 2 {
			return usage()
		}
		for _, s := range segs {
			if !repoSegment.MatchString(s) {
				return usage()
			}
		}
	}
	// A checkout's remote names the forge too, so -R inside one reads
	// that checkout's forge, not the default.
	if cwd, err := e.Getwd(); err == nil {
		if kind, root := checkoutKind(cwd); kind != "" {
			remote = e.checkoutRemote(ctx, kind, root)
		}
	} else if !repoSet {
		return v.refuse(1, "refused", "this directory cannot be read: "+show(err.Error()), false, nil)
	}
	if !repoSet {
		var serr error
		if segs, serr = remoteSegments(remote); serr != nil {
			return v.refuse(2, "usage", "no repository: this directory is not a checkout of a repository of the forge, and no -R was given", false,
				&nextstep.Next{Say: "Name the repository with -R OWNER/NAME."})
		}
	}
	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)
	}
	ctx, cancel := context.WithTimeout(ctx, 60*time.Second)
	defer cancel()

	path := "/r/" + strings.Join(segs, "/") + "/ticket"
	q := url.Values{}
	if sub == "show" {
		path += "/" + url.PathEscape(id)
	} else {
		q.Set("limit", "200")
		if status != "" {
			q.Set("status", status)
		}
	}
	body, err := e.getRaw(ctx, base, rec.Token, path, q)
	if err != nil {
		var re *forgeRefusal
		switch {
		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, &re):
			if re.Status == http.StatusServiceUnavailable {
				return v.busy(re.RetryAfter)
			}
			return v.refuse(1, "refused", show(re.Error()), false, re.apiRefusal.Next)
		}
		return e.netRefuse(ctx, v, base, err, "quarry ticket")
	}
	if asJSON {
		fmt.Fprintln(e.Stdout, strings.TrimSpace(string(body)))
		return 0
	}
	if sub == "list" {
		var list struct {
			Tickets []ticketRow `json:"tickets"`
		}
		if json.Unmarshal(body, &list) != nil {
			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"})
		}
		for _, t := range list.Tickets {
			short := t.ID
			if len(short) > 10 {
				short = short[:10]
			}
			fmt.Fprintf(e.Stdout, "#%d\t%s\t%s\t%s\t%s\n", t.Number, short, t.Status, t.Type, show(t.Title))
		}
		return 0
	}
	var got ticketAnswer
	if json.Unmarshal(body, &got) != nil {
		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"})
	}
	t := got.Ticket
	if got.Number > 0 {
		fmt.Fprintf(e.Stdout, "number: %d\n", got.Number)
	}
	fmt.Fprintf(e.Stdout, "id: %s\ncreated: %s\nupdated: %s\n", t.ID, t.Created, t.Updated)
	for _, f := range t.Fields {
		if f.Value != "" {
			fmt.Fprintf(e.Stdout, "%s: %s\n", show(f.Name), show(f.Value))
		}
	}
	if t.Description != "" {
		fmt.Fprintf(e.Stdout, "\n%s\n", strings.TrimRight(t.Description, "\n"))
	}
	for _, c := range t.Comments {
		who := c.Login
		if who == "" {
			who = c.Username
		}
		fmt.Fprintf(e.Stdout, "\n--- %s, %s\n%s\n", show(who), c.Date, strings.TrimRight(c.Body, "\n"))
	}
	return 0
}

// getRaw reads one forge route with the token and returns the body as
// sent. A 401 is errTokenDead; any other non-200 is a *forgeRefusal.
func (e *Env) getRaw(ctx context.Context, base *url.URL, token, path string, q url.Values) ([]byte, error) {
	u, err := apiTarget(base, apiPrefix+path)
	if err != nil {
		return nil, err
	}
	u.RawQuery = q.Encode()
	req, err := http.NewRequestWithContext(ctx, "GET", u.String(), nil)
	if err != nil {
		return nil, 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 nil, err
	}
	defer resp.Body.Close()
	body, err := io.ReadAll(io.LimitReader(resp.Body, pickupBodyMax))
	if err != nil {
		return nil, err
	}
	switch {
	case resp.StatusCode == http.StatusUnauthorized:
		return nil, errTokenDead
	case resp.StatusCode != http.StatusOK:
		r := &forgeRefusal{Status: resp.StatusCode, RetryAfter: retryAfter(resp)}
		_ = json.Unmarshal(body, &r.apiRefusal)
		return nil, r
	}
	return body, nil
}