Skip to content
quarry Artifact [888c1e418b]
Login

Artifact [888c1e418b]

Artifact 888c1e418b4886a91c0df4845ddf2fc576fa28c829509a13aadcd87d942dd971:


package pickupclient

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

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

const ciRerunHelp = `usage: quarry ci rerun RUN [-R OWNER/NAME] [--json]

Run a finished CI run again: a new run of the same pipeline at the same
check-in, linked to the old one. Prints the new run's id. Needs the
repository's admin capability.

  RUN   a run id, or the start of one
  -R    the repository, as OWNER/NAME; without it, the repository of
        this checkout's remote

A run still queued or running is refused: cancel it first.

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

Example:
  quarry ci rerun 3f9a1c -R dmestas/quarry
`

// CIRerun is quarry ci rerun.
func CIRerun(ctx context.Context, args []string, e *Env) int {
	e.fillLogin()
	args, asJSON := stripJSON(args)
	v := voice{e, e.named("ci rerun"), asJSON, nil}
	usage := func() int {
		return v.refuse(2, "usage", "usage: quarry ci rerun RUN [-R OWNER/NAME] [--json] (quarry ci rerun --help)", false,
			&nextstep.Next{Say: "See quarry ci rerun --help.", Cmd: "quarry ci rerun --help"})
	}
	var id, repoArg 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, ciRerunHelp)
			return 0
		case a == "-R" || a == "--repo":
			if i+1 >= len(args) {
				return usage()
			}
			repoArg, repoSet = args[i+1], true
			i++
		case strings.HasPrefix(a, "-"), id != "":
			return usage()
		default:
			id = a
		}
	}
	if id == "" || strings.ContainsAny(id, "/?#") {
		return usage()
	}
	var remote *url.URL
	var segs []string
	if repoSet {
		segs = strings.Split(repoArg, "/")
		if repoArg == "" || len(segs) > 2 {
			return usage()
		}
		for _, s := range segs {
			if !repoSegment.MatchString(s) {
				return usage()
			}
		}
	}
	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()

	var got struct {
		OK    bool   `json:"ok"`
		RunID string `json:"runId"`
	}
	path := "/r/" + strings.Join(segs, "/") + "/ci/runs/" + url.PathEscape(id) + "/rerun"
	if err := e.postJSON(ctx, base, rec.Token, path, struct{}{}, &got); 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)
		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"})
		}
		return e.netRefuse(ctx, v, base, err, "quarry ci rerun")
	}
	if asJSON {
		v.print(got)
		return 0
	}
	fmt.Fprintln(e.Stdout, show(got.RunID))
	return 0
}