Skip to content
quarry Artifact [a096685205]
Login

Artifact [a096685205]

Artifact a0966852056ab73b204f8e63830dba6f3ea21c6c045689102138501e43723675:


// Package quarrycli is the command line of the downloadable quarry
// program: the verb table, the screens that teach it, and the verbs
// that need no forge code. It imports nothing server side, so the small
// client build stays small (TestClientImportsNoServer holds it there).
package quarrycli

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

	"craftdesign.group/quarry/internal/pickupclient"
	"craftdesign.group/quarry/internal/runner"
	"craftdesign.group/quarry/internal/runner/install"
)

// Env is what the verbs run against. Zero values are the real ones.
type Env struct {
	Stdout, Stderr io.Writer
	Version        string
	// Pickup seeds the login and pickup verbs' environment; its writers
	// are replaced with Stdout and Stderr.
	Pickup pickupclient.Env
	Client *http.Client
}

// Command is one verb. Name is the full spelling ("auth login"); Aliases
// are single words that mean the same thing.
type Command struct {
	Name    string
	Aliases []string
	Usage   string // the verb with its arguments, as typed after "quarry"
	Summary string
	// Front marks the verbs the bare screen lists, in table order.
	Front bool
	// Lead, when set, puts the verb on the bare screen under that label
	// ("Then:", "Stuck:") after the front verbs.
	Lead string
	// Planned verbs are named but not in this build yet. The bare screen
	// shows no planned verb; clearing the flag is what puts one there.
	Planned bool
	// Hidden verbs are left out of help.
	Hidden bool
	run    func(ctx context.Context, args []string, e *Env) int
}

var table []*Command

func init() {
	table = []*Command{
		{Name: "auth login", Aliases: []string{"login"}, Usage: "auth login", Front: true,
			Summary: "log this machine in as you (one approval, in a browser)",
			run: func(ctx context.Context, a []string, e *Env) int {
				return pickupclient.Login(ctx, a, e.pickup())
			}},
		{Name: "auth status", Aliases: []string{"whoami"}, Usage: "auth status", Front: true,
			Summary: "who this machine is logged in as, and what that token reaches",
			run: func(ctx context.Context, a []string, e *Env) int {
				return pickupclient.Whoami(ctx, a, e.pickup())
			}},
		{Name: "auth logout", Usage: "auth logout",
			Summary: "end this machine's token on the forge, then forget it",
			run: func(ctx context.Context, a []string, e *Env) int {
				return pickupclient.Logout(ctx, a, e.pickup())
			}},
		{Name: "repo clone", Usage: "repo clone O/N", Front: true, Planned: true,
			Summary: "copy a repository here; zit then syncs with no password"},
		{Name: "land", Usage: "land", Front: true, Planned: true,
			Summary: "push this branch, open its landing, land it when CI is green"},
		{Name: "status", Usage: "status", Lead: "Then:", Planned: true,
			Summary: "what is my work waiting on?"},
		{Name: "doctor", Usage: "doctor", Lead: "Stuck:", Planned: true,
			Summary: "what is wrong here, and the command that fixes it"},
		{Name: "pickup", Usage: "pickup new | collect URL ...",
			Summary: "collect a credential a person approved for this machine",
			run: func(ctx context.Context, a []string, e *Env) int {
				return pickupclient.Command(ctx, a, e.pickup())
			}},
		{Name: "runner", Usage: "runner [flags] URL",
			Summary: "run a repository's CI on this machine",
			run: func(ctx context.Context, a []string, e *Env) int {
				if err := runner.Main(a, "quarry runner", e.Version); err != nil {
					return runnerFail(e, err)
				}
				return 0
			}},
		{Name: "version", Usage: "version [URL]",
			Summary: "the client's version, and the forge's if it answers",
			run:     versionCmd},
		{Name: "help", Usage: "help [--json]",
			Summary: "every command; --json describes them for a program",
			run:     helpCmd},
		{Name: "ui", Hidden: true, run: forgeOnly},
		{Name: "serve", Hidden: true, run: forgeOnly},
	}
}

// Commands is every verb, in the order help lists them.
func Commands() []*Command {
	var out []*Command
	for _, c := range table {
		if !c.Hidden {
			out = append(out, c)
		}
	}
	return out
}

// FrontDoor is the verbs the bare screen lists: front verbs that work.
func FrontDoor() []*Command {
	var out []*Command
	for _, c := range table {
		if c.Front && !c.Planned {
			out = append(out, c)
		}
	}
	return out
}

// Resolve finds the verb args start with, by full name or alias, and
// returns what is left for it. Nil when args name none.
func Resolve(args []string) (*Command, []string) {
	for _, c := range table {
		words := strings.Fields(c.Name)
		if len(args) >= len(words) && strings.Join(args[:len(words)], " ") == c.Name {
			return c, args[len(words):]
		}
	}
	if len(args) > 0 {
		for _, c := range table {
			for _, a := range c.Aliases {
				if a == args[0] {
					return c, args[1:]
				}
			}
		}
	}
	return nil, args
}

func (e *Env) pickup() *pickupclient.Env {
	p := e.Pickup
	p.Stdout, p.Stderr = e.Stdout, e.Stderr
	if e.Client != nil && p.Client == nil {
		p.Client = e.Client
	}
	return &p
}

// Run is the quarry program: args are what follows its name. The exit
// status is the verb's: 0 done, 1 refused, 2 usage, 3 still waiting, 4 not
// logged in.
func Run(ctx context.Context, args []string, e *Env) int {
	if e.Stdout == nil {
		e.Stdout = os.Stdout
	}
	if e.Stderr == nil {
		e.Stderr = os.Stderr
	}
	if len(args) == 0 {
		bare(e)
		return 0
	}
	switch args[0] {
	case "-h", "--help":
		return helpCmd(ctx, nil, e)
	case "-v", "--version":
		return versionCmd(ctx, nil, e)
	}
	c, rest := Resolve(args)
	if c == nil {
		if args[0] == "auth" {
			fmt.Fprintln(e.Stderr, "quarry auth: say what to do: login, status or logout (quarry help)")
		} else {
			fmt.Fprintf(e.Stderr, "quarry: no command %q (quarry help lists them)\n", args[0])
		}
		return 2
	}
	if c.Planned {
		fmt.Fprintf(e.Stderr, "quarry %s: not in this build yet (quarry help lists what is)\n", c.Name)
		return 1
	}
	return c.run(ctx, rest, e)
}

func runnerFail(e *Env, err error) int {
	if ee, ok := err.(*install.ExitError); ok {
		if ee.Msg != "" {
			fmt.Fprintln(e.Stderr, "quarry runner:", ee.Msg)
		}
		return ee.Code
	}
	fmt.Fprintln(e.Stderr, "quarry runner:", err)
	return 1
}

func forgeOnly(_ context.Context, _ []string, e *Env) int {
	fmt.Fprintln(e.Stderr, "quarry: this command belongs to the forge's own quarry program, which this download does not carry; it is installed with the forge.")
	return 1
}

// pad is the width of the verb column: the longest front-door usage.
func pad(cs []*Command) int {
	w := 0
	for _, c := range cs {
		if len(c.Usage) > w {
			w = len(c.Usage)
		}
	}
	return w + 2
}

func bare(e *Env) {
	front := FrontDoor()
	w := pad(front)
	fmt.Fprintln(e.Stdout, "quarry: work on a quarry forge from a terminal.")
	fmt.Fprintln(e.Stdout)
	for _, c := range front {
		fmt.Fprintf(e.Stdout, "  quarry %-*s%s\n", w, c.Usage, c.Summary)
	}
	fmt.Fprintln(e.Stdout)
	for _, c := range table {
		if c.Lead != "" && !c.Planned {
			fmt.Fprintf(e.Stdout, "%-8s quarry %-9s%s\n", c.Lead, c.Name, c.Summary)
		}
	}
	fmt.Fprintln(e.Stdout, "More:    quarry help     every command      quarry help --json   the same, for a program")
}

func helpCmd(_ context.Context, args []string, e *Env) int {
	asJSON := false
	for _, a := range args {
		if a == "--json" || a == "-F=json" {
			asJSON = true
		} else {
			fmt.Fprintln(e.Stderr, "usage: quarry help [--json]")
			return 2
		}
	}
	cs := Commands()
	if asJSON {
		type jc struct {
			Name    string   `json:"name"`
			Aliases []string `json:"aliases"`
			Usage   string   `json:"usage"`
			Summary string   `json:"summary"`
			Planned bool     `json:"planned"`
		}
		doc := struct {
			Name     string `json:"name"`
			Version  string `json:"version"`
			Commands []jc   `json:"commands"`
		}{Name: "quarry", Version: e.Version, Commands: []jc{}}
		for _, c := range cs {
			al := c.Aliases
			if al == nil {
				al = []string{}
			}
			doc.Commands = append(doc.Commands, jc{c.Name, al, "quarry " + c.Usage, c.Summary, c.Planned})
		}
		b, _ := json.Marshal(doc)
		fmt.Fprintln(e.Stdout, string(b))
		return 0
	}
	w := pad(cs)
	fmt.Fprintln(e.Stdout, "quarry: work on a quarry forge from a terminal.")
	fmt.Fprintln(e.Stdout)
	for _, c := range cs {
		note := ""
		if len(c.Aliases) > 0 {
			note = "  (also: quarry " + strings.Join(c.Aliases, ", quarry ") + ")"
		}
		if c.Planned {
			note = "  (coming)"
		}
		fmt.Fprintf(e.Stdout, "  quarry %-*s%s%s\n", w, c.Usage, c.Summary, note)
	}
	fmt.Fprintln(e.Stdout)
	fmt.Fprintln(e.Stdout, "Exit: 0 done, 1 refused, 2 usage, 3 still waiting, 4 not logged in.")
	return 0
}

// versionCmd prints this program's version and, when the forge answers
// within a few seconds, the forge's. An unreachable forge is not a
// failure: the client's own version is the answer.
func versionCmd(ctx context.Context, args []string, e *Env) int {
	if len(args) > 1 {
		fmt.Fprintln(e.Stderr, "usage: quarry version [URL]")
		return 2
	}
	fmt.Fprintf(e.Stdout, "quarry %s (client)\n", e.Version)
	raw := ""
	if len(args) == 1 {
		raw = args[0]
	} else {
		dir := e.Pickup.ConfigDir
		if dir == "" {
			dir = pickupclient.ConfigDir()
		}
		raw = pickupclient.DefaultHost(dir)
	}
	base, err := url.Parse(raw)
	if err != nil || base.Host == "" {
		fmt.Fprintf(e.Stderr, "quarry version: %q is not a forge address\n", raw)
		return 2
	}
	ctx, cancel := context.WithTimeout(ctx, 4*time.Second)
	defer cancel()
	req, err := http.NewRequestWithContext(ctx, "GET", base.ResolveReference(&url.URL{Path: "/api/v1/version"}).String(), nil)
	if err != nil {
		return 0
	}
	c := e.Client
	if c == nil {
		c = &http.Client{}
	}
	resp, err := c.Do(req)
	if err != nil {
		return 0
	}
	defer resp.Body.Close()
	var v struct {
		Version string `json:"version"`
	}
	if resp.StatusCode == http.StatusOK && json.NewDecoder(io.LimitReader(resp.Body, 1<<16)).Decode(&v) == nil && v.Version != "" {
		fmt.Fprintf(e.Stdout, "quarry %s (forge %s)\n", clean(v.Version), base.Host)
	}
	return 0
}

// clean keeps a server string to printable characters.
func clean(s string) string {
	return strings.Map(func(r rune) rune {
		if r < 0x20 || r == 0x7f || (r >= 0x80 && r <= 0x9f) {
			return -1
		}
		return r
	}, s)
}