Add pinned tools for source-only releases

This commit is contained in:
2026-12-05 22:30:21 +00:00
parent d185df5fd1
commit 6f01e9ef0a
14 changed files with 519 additions and 4 deletions

View File

@@ -1742,7 +1742,11 @@ func writeDeliveryRelease(w http.ResponseWriter, baseURL string, data *deliveryS
if product == "" {
product = "Example Product"
}
_ = json.NewEncoder(w).Encode(map[string]any{"id": 10, "html_url": baseURL + "/releases/10", "tag_name": data.tag, "target_commitish": data.commit, "name": product + " v1.2.3", "body": data.noteBody, "draft": false, "prerelease": false})
version := data.tag
if slash := strings.LastIndex(version, "/"); slash >= 0 {
version = version[slash+1:]
}
_ = json.NewEncoder(w).Encode(map[string]any{"id": 10, "html_url": baseURL + "/releases/10", "tag_name": data.tag, "target_commitish": data.commit, "name": product + " " + version, "body": data.noteBody, "draft": false, "prerelease": false})
}
func writeDeliveryProfile(t *testing.T, repository string, settings cli.Settings) {

View File

@@ -0,0 +1,338 @@
package main
import (
"errors"
"fmt"
"io/fs"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"golang.org/x/mod/modfile"
"golang.org/x/mod/module"
)
func TestSourceOnlyWorkflowUsesPinFromVerifiedTag(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("POSIX workflow")
}
root := cliRepositoryRoot(t)
repo := filepath.Join(t.TempDir(), "configuration")
if err := os.Mkdir(repo, 0700); err != nil {
t.Fatal(err)
}
copyExampleTree(t, filepath.Join(root, "examples", "source-only"), repo)
cliGitRun(t, repo, "init", "--initial-branch=main")
cliGitRun(t, repo, "config", "user.name", "ReleaseKit Test")
cliGitRun(t, repo, "config", "user.email", "releasekit@example.test")
state := &deliveryServerState{data: deliveryServerData{tag: "2026-12-05", product: "Example Configuration"}}
server := newDeliveryServer(t, state)
defer server.Close()
profile := fmt.Sprintf(`{"product":"Example Configuration","source":{},"version":{"format":"date"},"delivery":{"forge":"gitea","base_url":%q,"owner":"owner","repository":"example","credentials":{"ci":{"token_environment_variable":"RELEASEKIT_GITEA_TOKEN"}}}}`, server.URL)
writeRepositoryFile(t, repo, "releasekit.json", profile)
writeRepositoryFile(t, repo, ".releasekit-version", "v0.2.197\n")
cliGitRun(t, repo, "add", ".")
cliGitRun(t, repo, "commit", "-m", "prepare configuration")
commit := cliGitOutput(t, repo, "rev-parse", "HEAD")
state.update(func(data *deliveryServerData) { data.commit = commit })
cliGitRun(t, repo, "-c", "tag.gpgsign=false", "tag", "-a", "2026-12-05", "-m", "Example Configuration 2026-12-05")
tagObject := cliGitOutput(t, repo, "rev-parse", "refs/tags/2026-12-05")
remote := filepath.Join(t.TempDir(), "origin.git")
cliGitRun(t, repo, "init", "--bare", remote)
cliGitRun(t, repo, "remote", "add", "origin", remote)
cliGitRun(t, repo, "push", "origin", "main", "refs/tags/2026-12-05")
writeRepositoryFile(t, repo, ".releasekit-version", "v0.2.198\n")
cliGitRun(t, repo, "add", ".releasekit-version")
cliGitRun(t, repo, "commit", "-m", "change tool pin")
otherCommit := cliGitOutput(t, repo, "rev-parse", "HEAD")
proxy := currentReleaseKitProxy(t, root, "v0.2.197")
environment := map[string]string{"CI_WORKSPACE": repo, "CI_COMMIT_TAG": "2026-12-05", "CI_COMMIT_SHA": tagObject, "RELEASEKIT_GITEA_TOKEN": "fixture-token", "GOOS": "windows", "GOARCH": "386"}
useSyntheticModuleProxy(t, environment, "file://"+filepath.ToSlash(proxy))
workflow, err := os.ReadFile(filepath.Join(repo, ".woodpecker", "delivery.yml"))
if err != nil {
t.Fatal(err)
}
block, err := extractWoodpeckerCommand(string(workflow), "deliver")
if err != nil {
t.Fatal(err)
}
block = strings.ReplaceAll(block, "$${", "${")
environment["CI_COMMIT_SHA"] = otherCommit
mismatch, mismatchErr := executeWoodpeckerBlock(block, repo, environment)
if mismatchErr == nil || !strings.Contains(mismatch, "resolves to commit") || state.snapshot().apiRequests != 0 {
t.Fatalf("mismatched event was not rejected before delivery: %v: %s", mismatchErr, mismatch)
}
if _, err := os.Stat(filepath.Join(repo, ".releasekit", "tools")); !os.IsNotExist(err) {
t.Fatalf("mismatched event installed a tool: %v", err)
}
environment["CI_COMMIT_SHA"] = tagObject
output := runWoodpeckerBlock(t, block, repo, environment)
if !strings.Contains(output, "state complete") || !strings.Contains(output, commit) || !strings.Contains(output, "2026-12-05") || state.snapshot().releaseCreates != 1 || state.snapshot().assetUploads != 0 {
t.Fatalf("workflow output = %q", output)
}
installed := filepath.Join(repo, ".releasekit", "tools", "v0.2.197", runtime.GOOS+"-"+runtime.GOARCH, "releasekit")
version, err := exec.Command(installed, "version").Output()
if err != nil || !strings.Contains(string(version), "v0.2.197") {
t.Fatalf("installed tagged tool version = %q, error = %v", version, err)
}
if status := cliGitOutput(t, repo, "status", "--porcelain", "--untracked-files=all"); status != "" {
t.Fatalf("installed tool changed checkout state: %s", status)
}
}
func TestSourceOnlyInstalledToolRecoveryAfterLauncherExit(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("POSIX launcher")
}
root := cliRepositoryRoot(t)
repo, remote := newSimplePublishRepository(t, false)
if err := os.Mkdir(filepath.Join(repo, "scripts"), 0700); err != nil {
t.Fatal(err)
}
copyExampleTree(t, filepath.Join(root, "examples", "source-only", "scripts"), filepath.Join(repo, "scripts"))
cliGitRun(t, repo, "rm", "go.mod")
writeRepositoryFile(t, repo, ".gitignore", ".releasekit/\n")
writeRepositoryFile(t, repo, ".releasekit-version", "v0.2.197\n")
writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Example Product","source":{},"version":{"format":"date"}}`)
writeRepositoryFile(t, repo, "docs/releases/2026-12-01.md", "# Example Product 2026-12-01\n\nRelease.\n")
cliGitRun(t, repo, "add", ".")
cliGitRun(t, repo, "commit", "-m", "configure source release")
cliGitRun(t, repo, "push", "origin", "main")
if err := os.WriteFile(filepath.Join(remote, "hooks", "pre-receive"), []byte("#!/bin/sh\nexit 1\n"), 0700); err != nil {
t.Fatal(err)
}
proxy := currentReleaseKitProxy(t, root, "v0.2.197")
environment := map[string]string{}
useSyntheticModuleProxy(t, environment, "file://"+filepath.ToSlash(proxy))
for key, value := range environment {
t.Setenv(key, value)
}
launcher := exec.Command(filepath.Join(repo, "scripts", "release"), "2026-12-01")
output, err := launcher.CombinedOutput()
var exit *exec.ExitError
if !errors.As(err, &exit) || exit.ExitCode() != 1 {
t.Fatalf("publication: %v: %s", err, output)
}
command := outputLineValue(string(output), "recovery command: ")
installed := filepath.Join(repo, ".releasekit", "tools", "v0.2.197", runtime.GOOS+"-"+runtime.GOARCH, "releasekit")
if command == "" || !strings.Contains(command, shellQuote(installed)) {
t.Fatalf("recovery did not select installed tool: %s", output)
}
shim := t.TempDir()
marker := filepath.Join(shim, "go-invoked")
if err := os.WriteFile(filepath.Join(shim, "go"), []byte("#!/bin/sh\n: > \"$RELEASEKIT_GO_MARKER\"\nexit 99\n"), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("RELEASEKIT_GO_MARKER", marker)
t.Setenv("PATH", shim+string(os.PathListSeparator)+os.Getenv("PATH"))
recovery := exec.Command("sh", "-c", command)
recovery.Dir = t.TempDir()
recovered, err := recovery.CombinedOutput()
if !errors.As(err, &exit) || exit.ExitCode() != 1 || !strings.Contains(string(recovered), "tag=2026-12-01 state=not_published") {
t.Fatalf("recovery: %v: %s", err, recovered)
}
if _, err := os.Stat(marker); !os.IsNotExist(err) {
t.Fatalf("recovery invoked Go after installation: %v", err)
}
}
// currentReleaseKitProxy packages the current CLI as a synthetic tool version
// and copies its prepared dependencies into a test-owned file proxy.
func currentReleaseKitProxy(t *testing.T, root, version string) string {
t.Helper()
proxy := t.TempDir()
moduleBytes, err := os.ReadFile(filepath.Join(root, "go.mod"))
if err != nil {
t.Fatal(err)
}
declaration, err := modfile.Parse("go.mod", moduleBytes, nil)
if err != nil {
t.Fatal(err)
}
files := map[string]string{}
for _, name := range []string{"buildinfo", "cmd/releasekit", "internal"} {
err := filepath.WalkDir(filepath.Join(root, filepath.FromSlash(name)), func(path string, entry fs.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
if entry.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
return nil
}
relative, err := filepath.Rel(root, path)
if err != nil {
return err
}
data, err := os.ReadFile(path)
if err != nil {
return err
}
files[filepath.ToSlash(relative)] = string(data)
return nil
})
if err != nil {
t.Fatal(err)
}
}
entries, err := os.ReadDir(root)
if err != nil {
t.Fatal(err)
}
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".go") || strings.HasSuffix(entry.Name(), "_test.go") {
continue
}
data, err := os.ReadFile(filepath.Join(root, entry.Name()))
if err != nil {
t.Fatal(err)
}
files[entry.Name()] = string(data)
}
writeModuleProxyVersion(t, proxy, "go.maximumdirect.net/releasekit", version, string(moduleBytes), files)
goCommand := exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go"), "env", "GOMODCACHE")
goCommand.Dir = root
cache, err := goCommand.Output()
if err != nil {
t.Fatalf("find prepared module cache: %v", err)
}
for _, dependency := range declaration.Require {
path, err := module.EscapePath(dependency.Mod.Path)
if err != nil {
t.Fatal(err)
}
version, err := module.EscapeVersion(dependency.Mod.Version)
if err != nil {
t.Fatal(err)
}
source := filepath.Join(strings.TrimSpace(string(cache)), "cache", "download", filepath.FromSlash(path), "@v")
target := filepath.Join(proxy, filepath.FromSlash(path), "@v")
if err := os.MkdirAll(target, 0700); err != nil {
t.Fatal(err)
}
for _, suffix := range []string{".info", ".mod", ".zip"} {
name := version + suffix
contents, err := os.ReadFile(filepath.Join(source, name))
if err != nil {
t.Fatalf("read prepared dependency %s: %v", name, err)
}
if err := os.WriteFile(filepath.Join(target, name), contents, 0600); err != nil {
t.Fatal(err)
}
}
}
return proxy
}
func TestSourceOnlyToolPinInstallsHostAndRetainsExecutable(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("POSIX launcher")
}
root := cliRepositoryRoot(t)
repo := filepath.Join(t.TempDir(), "configuration")
if err := os.Mkdir(repo, 0700); err != nil {
t.Fatal(err)
}
copyExampleTree(t, filepath.Join(root, "examples", "source-only"), repo)
cliGitRun(t, repo, "init", "--initial-branch=main")
proxy := writeWorkflowToolProxy(t)
env := map[string]string{}
useSyntheticModuleProxy(t, env, "file://"+filepath.ToSlash(proxy))
for key, value := range env {
t.Setenv(key, value)
}
t.Setenv("GOOS", "windows")
t.Setenv("GOARCH", "386")
stub := filepath.Join(t.TempDir(), "consumer-tool")
if err := os.WriteFile(stub, []byte("#!/bin/sh\nprintf 'delegated %s\\n' \"$*\"\nexit 23\n"), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("RELEASEKIT_TEST_BINARY", stub)
writeRepositoryFile(t, repo, ".releasekit-version", " v0.2.197\r\n")
command := func(name string, args ...string) ([]byte, error) {
process := exec.Command(filepath.Join(repo, "scripts", name), args...)
process.Dir = repo
return process.Output()
}
pathBytes, err := command("releasekit-tool")
if err != nil {
t.Fatalf("install: %v: %s", err, pathBytes)
}
path := strings.TrimSpace(string(pathBytes))
if !filepath.IsAbs(path) || !strings.Contains(path, "v0.2.197") || !strings.Contains(path, runtime.GOOS+"-"+runtime.GOARCH) {
t.Fatalf("installed path = %q", path)
}
output, err := command("releasekit", "version")
var exit *exec.ExitError
if !errors.As(err, &exit) || exit.ExitCode() != 23 || !strings.Contains(string(output), "tool-version=v0.2.197") || !strings.Contains(string(output), "delegated version") {
t.Fatalf("launcher: %v: %s", err, output)
}
output, err = command("releasekit", "test", "--repo", repo, "--json")
if !errors.As(err, &exit) || exit.ExitCode() != 23 || !strings.Contains(string(output), "delegated test --repo "+repo+" --json") {
t.Fatalf("diagnostic invocation: %v: %s", err, output)
}
if info, err := os.Stat(path); err != nil {
t.Fatalf("installed executable did not survive launcher: %v", err)
} else if info.Mode().Perm()&0077 != 0 {
t.Fatalf("installed executable is not private: %v", info.Mode())
}
t.Setenv("GOPROXY", "off")
t.Setenv("GOMODCACHE", t.TempDir())
reused, err := command("releasekit-tool")
if err != nil || strings.TrimSpace(string(reused)) != path {
t.Fatalf("reuse without proxy: %v: %s", err, reused)
}
t.Setenv("GOPROXY", env["GOPROXY"])
t.Setenv("GOMODCACHE", env["GOMODCACHE"])
writeRepositoryFile(t, repo, ".releasekit-version", "v0.2.198\n")
other, err := command("releasekit-tool")
if err != nil || strings.TrimSpace(string(other)) == path || !strings.Contains(string(other), "v0.2.198") {
t.Fatalf("changed pin install: %v: %s", err, other)
}
for _, invalid := range []string{"", "v0.2.197 v0.2.198", "v0.2.197-rc1", "v00.2.197"} {
writeRepositoryFile(t, repo, ".releasekit-version", invalid)
output, err := command("releasekit-tool")
if !errors.As(err, &exit) || exit.ExitCode() != 2 || !strings.Contains(string(exit.Stderr), "one stable module version") {
t.Fatalf("pin %q: %v: %s", invalid, err, output)
}
}
writeRepositoryFile(t, repo, ".releasekit-version", "v0.2.199\n")
output, err = command("releasekit-tool")
if err == nil {
t.Fatalf("unavailable install succeeded: %s", output)
}
missing := filepath.Join(repo, ".releasekit", "tools", "v0.2.199", runtime.GOOS+"-"+runtime.GOARCH, "releasekit")
if _, err := os.Stat(missing); !os.IsNotExist(err) {
t.Fatalf("failed install left executable: %v", err)
}
temporary, err := filepath.Glob(filepath.Join(filepath.Dir(missing), ".install.*"))
if err != nil || len(temporary) != 0 {
t.Fatalf("failed install left temporary files: %v, error = %v", temporary, err)
}
shim := t.TempDir()
script := "#!/bin/sh\nif [ \"$1\" = install ]; then printf partial > \"$GOBIN/releasekit\"; chmod +x \"$GOBIN/releasekit\"; exit 37; fi\nexec \"$RELEASEKIT_TEST_GO\" \"$@\"\n"
if err := os.WriteFile(filepath.Join(shim, "go"), []byte(script), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("RELEASEKIT_TEST_GO", filepath.Join(runtime.GOROOT(), "bin", "go"))
t.Setenv("PATH", shim+string(os.PathListSeparator)+os.Getenv("PATH"))
writeRepositoryFile(t, repo, ".releasekit-version", "v0.2.200\n")
output, err = command("releasekit-tool")
if !errors.As(err, &exit) || exit.ExitCode() != 37 {
t.Fatalf("partial install exit = %v: %s", err, output)
}
for _, launcher := range []string{"releasekit", "release"} {
output, err = command(launcher, "version")
if !errors.As(err, &exit) || exit.ExitCode() != 37 {
t.Fatalf("%s install failure exit = %v: %s", launcher, err, output)
}
}
failedDir := filepath.Join(repo, ".releasekit", "tools", "v0.2.200", runtime.GOOS+"-"+runtime.GOARCH)
if _, err := os.Stat(filepath.Join(failedDir, "releasekit")); !os.IsNotExist(err) {
t.Fatalf("partial install left a usable executable: %v", err)
}
if temporary, err := filepath.Glob(filepath.Join(failedDir, ".install.*")); err != nil || len(temporary) != 0 {
t.Fatalf("partial install left temporary files: %v, error = %v", temporary, err)
}
}

View File

@@ -1,8 +1,23 @@
# Adopt ReleaseKit
Use a versioned Go tool dependency when ReleaseKit provides the repository's
release commands. This records the CLI in `go.mod` and keeps it available to
maintainers without adding imports to application or library code.
Use a versioned Go tool dependency when a Go module provides the repository's
release commands. Source-only repositories can instead use the installed-tool
launcher described below.
## Source-only repositories
The [source-only example](../../examples/source-only/README.md) provides a
profile, local launcher, and tag-verified Woodpecker workflow without requiring
an application `go.mod`. Commit a root `.releasekit-version` containing one
stable ReleaseKit module version. Select a published version implementing the
profile and workflow; the example's current pin illustrates syntax and must be
updated when the next release is available.
The maintained installer uses the same committed pin locally and in CI,
installs the host executable in the ignored `.releasekit/tools` directory,
and preserves Go proxy and checksum settings. A failed install does not leave a
usable partial executable. The durable executable also supports the exact
publication-recovery command printed after an uncertain push.
## CLI tool dependency

View File

@@ -388,6 +388,13 @@ SSH-agent authentication without a private-key file, and no remote writes.
## Stage 8: Supply one tool pin for source-only repositories
**Completed:** Source-only launchers install and retain a host-specific pinned
tool, and the tagged workflow selects the pin after verifying the event commit.
The documented `v0.10.0` pin remains a syntax placeholder for this sprint.
Isolated local-proxy tests exercise current-source installation, delivery,
failure cleanup, pin changes, and recovery without Go after launcher exit. The
offline `go test ./...` suite and `go run ./internal/apicheck` pass.
**Work:** add maintained source-only launcher/bootstrap examples and shared
installation guidance; extend recovery tooling where needed.

1
examples/source-only/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
.releasekit/

View File

@@ -0,0 +1 @@
v0.10.0

View File

@@ -0,0 +1,31 @@
when:
- event: tag
ref: refs/tags/20*
steps:
- name: deliver
image: golang:1.27.4-bookworm
environment:
# Woodpecker stores releasekit_gitea_token and injects this job variable.
RELEASEKIT_GITEA_TOKEN:
from_secret: releasekit_gitea_token
commands:
- |
set -eu
test -n "$${CI_COMMIT_TAG}"
test -n "$${CI_COMMIT_SHA}"
git check-ref-format "refs/tags/$${CI_COMMIT_TAG}"
git fetch origin "refs/tags/$${CI_COMMIT_TAG}:refs/tags/$${CI_COMMIT_TAG}"
tag_commit=$(git rev-parse --verify "refs/tags/$${CI_COMMIT_TAG}^{commit}")
expected_commit=$(git rev-parse --verify "$${CI_COMMIT_SHA}^{commit}")
if [ "$${tag_commit}" != "$${expected_commit}" ]; then
printf 'Tag %s resolves to commit %s; event %s resolves to commit %s\n' \
"$${CI_COMMIT_TAG}" "$${tag_commit}" "$${CI_COMMIT_SHA}" "$${expected_commit}" >&2
exit 1
fi
git checkout --detach "$${tag_commit}"
test "$(git rev-parse HEAD)" = "$${expected_commit}"
test -z "$(git status --porcelain --untracked-files=all)"
export GOWORK=off GOTOOLCHAIN=local
tool=$("$${CI_WORKSPACE}/scripts/releasekit-tool")
"$${tool}" ci-deliver --repo "$${CI_WORKSPACE}" --prepared --commit "$${expected_commit}" "$${CI_COMMIT_TAG}"

View File

@@ -0,0 +1,38 @@
# Source-only configuration example
This example releases JSON configuration without a Go module. Copy its files
into a repository, set the product and forge destination in `releasekit.json`,
and select a published ReleaseKit version that supports source-only calendar
releases in `.releasekit-version`. The committed `v0.10.0` value illustrates
the pin syntax only: it predates this feature and must be replaced before use.
The release that first supplies these interfaces has not yet been assigned a
version.
Install a local Go toolchain and Git. `scripts/releasekit-tool` reads the single
stable module version in the repository-root pin, installs the host executable
under the ignored `.releasekit/tools` directory, and prints its absolute path.
The private installation is reusable; installation can use the network, while
candidate validation remains offline. The launcher honors configured Go proxy,
checksum, and cache settings and disables automatic toolchain downloads and
workspace discovery. Update only the pin to select another tool version.
Save the local forge token in `.releasekit/gitea-token` with owner-only
permissions. The ignore rule keeps it out of ordinary commits; the optional
`validation.forbidden_files` check rejects a candidate that includes that
path. Configure the Woodpecker stored secret `releasekit_gitea_token`, which the
workflow injects as the CI job variable `RELEASEKIT_GITEA_TOKEN`.
After preparing a committed release note and authoritative `main`, run:
```sh
./scripts/releasekit validate
./scripts/release 2026-12-05
```
The second command publishes the source tag. The [delivery workflow](.woodpecker/delivery.yml)
checks out and verifies the event tag before reading its committed pin. It
installs the same version for the host and invokes `ci-deliver`; page delivery
is separate from successful source publication. `scripts/releasekit` forwards
other CLI commands, including recovery commands, to the installed executable.
The publication failure output identifies the durable executable and exact
attempt record to use after the original launcher exits.

View File

@@ -0,0 +1,4 @@
{
"service": "example",
"enabled": true
}

View File

@@ -0,0 +1,3 @@
# Example Configuration 2026-12-05
Publish the initial configuration.

View File

@@ -0,0 +1,16 @@
{
"product": "Example Configuration",
"source": {},
"version": {"format": "date"},
"validation": {"forbidden_files": [".releasekit/gitea-token"]},
"delivery": {
"forge": "gitea",
"base_url": "https://gitea.example",
"owner": "example",
"repository": "configuration",
"credentials": {
"local": {"token_file": ".releasekit/gitea-token"},
"ci": {"token_environment_variable": "RELEASEKIT_GITEA_TOKEN"}
}
}
}

View File

@@ -0,0 +1,5 @@
#!/bin/sh
set -eu
script_dir=$(CDPATH= cd "$(dirname "$0")" && pwd)
repository=$(git -C "$script_dir" rev-parse --show-toplevel)
exec "$script_dir/releasekit" publish --repo "$repository" "$@"

View File

@@ -0,0 +1,6 @@
#!/bin/sh
set -eu
export GOWORK=off GOTOOLCHAIN=local
script_dir=$(CDPATH= cd "$(dirname "$0")" && pwd)
tool=$("$script_dir/releasekit-tool")
exec "$tool" "$@"

View File

@@ -0,0 +1,46 @@
#!/bin/sh
# Install the selected host tool once and print its durable absolute path.
set -eu
umask 077
script_dir=$(CDPATH= cd "$(dirname "$0")" && pwd)
repository=$(git -C "$script_dir" rev-parse --show-toplevel)
pin=$repository/.releasekit-version
if [ ! -r "$pin" ]; then
printf 'ReleaseKit tool pin is unreadable: %s\n' "$pin" >&2
exit 2
fi
if version=$(LC_ALL=C awk '
{ gsub(/[[:space:]]+/, " "); for (i = 1; i <= NF; i++) { value = $i; count++ } }
END {
if (count != 1 || value !~ /^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/) exit 1
print value
}
' "$pin"); then :; else
printf 'ReleaseKit tool pin must contain one stable module version, such as v0.10.0: %s\n' "$pin" >&2
exit 2
fi
export GOWORK=off GOTOOLCHAIN=local
host_os=$(go env GOHOSTOS)
host_arch=$(go env GOHOSTARCH)
case $host_os in
windows) executable=releasekit.exe ;;
*) executable=releasekit ;;
esac
tool_dir=$repository/.releasekit/tools/$version/$host_os-$host_arch
tool=$tool_dir/$executable
if [ ! -x "$tool" ]; then
mkdir -p "$tool_dir"
temporary=$(mktemp -d "$tool_dir/.install.XXXXXX")
trap 'rm -rf "$temporary"' EXIT
trap 'exit 1' HUP INT TERM
if GOBIN=$temporary GOOS=$host_os GOARCH=$host_arch go install "go.maximumdirect.net/releasekit/cmd/releasekit@$version"; then :; else
status=$?
exit "$status"
fi
if [ ! -x "$temporary/$executable" ]; then
printf 'ReleaseKit installation produced no executable\n' >&2
exit 1
fi
mv "$temporary/$executable" "$tool"
fi
printf '%s\n' "$tool"