Files

52 lines
1.3 KiB
Go

package main
import (
"bytes"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
)
// goEnv is the environment every build and test runs with: no cgo, no
// enclosing go.work, the plugin's vendor folder.
func goEnv(goos, goarch string) []string {
env := append(os.Environ(), "CGO_ENABLED=0", "GOWORK=off")
if goos != "" {
env = append(env, "GOOS="+goos, "GOARCH="+goarch)
}
return env
}
// goRun runs a go command in dir and returns its combined output.
func goRun(dir string, env []string, args ...string) (string, error) {
cmd := exec.Command("go", args...)
cmd.Dir = dir
cmd.Env = env
var out bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &out
err := cmd.Run()
return out.String(), err
}
// buildWorker builds ./cmd/worker for this machine into a temporary folder.
func buildWorker(dir string) (string, func(), error) {
tmp, err := os.MkdirTemp("", "cletus-plugin-")
if err != nil {
return "", nil, err
}
cleanup := func() { os.RemoveAll(tmp) }
name := "worker"
if runtime.GOOS == "windows" {
name += ".exe"
}
bin := filepath.Join(tmp, name)
if out, err := goRun(dir, goEnv("", ""), "build", "-trimpath", "-o", bin, "./cmd/worker"); err != nil {
cleanup()
return "", nil, fmt.Errorf("the worker doesn't build:\n%s", out)
}
return bin, cleanup, nil
}