package runner
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path"
"runtime"
"strings"
"time"
"craftdesign.group/quarry/internal/runner/install"
)
// setupCommand says whether args open with install, doctor or
// uninstall. A URL or a flag never does, so a unit written before these
// existed runs the runner as it always did.
func setupCommand(args []string) (string, bool) {
if len(args) == 0 {
return "", false
}
switch args[0] {
case "install", "doctor", "uninstall":
return args[0], true
}
return "", false
}
// runSetup runs one of the three on this machine.
func runSetup(name string, args []string, version string) error {
e := install.Env{
Sys: install.HostSystem{},
HTTP: &http.Client{Timeout: 30 * time.Second},
Out: os.Stdout,
Getenv: os.Getenv,
Prompt: install.PromptSecret,
Version: version,
GOOS: runtime.GOOS,
Trunk: trunkHasCI,
}
ctx := context.Background()
switch name {
case "install":
return install.Install(ctx, e, args)
case "doctor":
return install.Doctor(ctx, e, args)
}
return install.Uninstall(ctx, e, args)
}
// trunkHasCI is whether trunk has something for a runner to run: files
// in ci/ (a workflow, or ci/runner.json). It asks the forge for the
// listing and unpacks nothing, since doctor runs as root.
func trunkHasCI(ctx context.Context, repoURL string) (bool, error) {
u, err := url.Parse(strings.TrimSuffix(repoURL, "/"))
if err != nil {
return false, err
}
repo := path.Base(u.Path)
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", u.Scheme+"://"+u.Host+"/api/v1/r/"+url.PathEscape(repo)+"/tree/trunk/ci", nil)
if err != nil {
return false, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return false, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return false, fmt.Errorf("the forge answered %d", resp.StatusCode)
}
var list struct {
Entries []json.RawMessage `json:"entries"`
}
if err := json.NewDecoder(io.LimitReader(resp.Body, 4<<20)).Decode(&list); err != nil {
return false, err
}
return len(list.Entries) > 0, nil
}