diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d298a2c..919ee9f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,48 +4,70 @@ on: pull_request: push: branches: [main] + workflow_call: + inputs: + ref: + description: Revision to verify + type: string + required: true + outputs: + sha: + description: Exact commit verified by all jobs + value: ${{ jobs.lint.outputs.sha }} permissions: contents: read concurrency: - group: ci-${{ github.ref }} - cancel-in-progress: true + group: ci-${{ github.workflow }}-${{ inputs.ref || github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: + lint: + name: lint + runs-on: ubuntu-latest + outputs: + sha: ${{ steps.revision.outputs.sha }} + steps: + - uses: actions/checkout@v7 + with: + ref: ${{ inputs.ref || github.sha }} + - id: revision + run: echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" + - uses: jdx/mise-action@v4 + with: + cache: true + - uses: actions/cache@v6 + with: + path: | + ~/go/pkg/mod + ~/.cache/go-build + ~/.cache/golangci-lint + key: ${{ runner.os }}-lint-${{ hashFiles('mise.toml', 'go.sum') }} + restore-keys: ${{ runner.os }}-lint- + - run: task check:versions deps lint + - run: task release:check + test: name: test (${{ matrix.os }}) + needs: lint runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: os: [ubuntu-latest, macos-latest] steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Install toolchain from mise.toml - uses: jdx/mise-action@v4 - - - name: Build - run: go build ./... - - - name: Vet - run: go vet ./... - - - name: Test - run: go test -count=1 ./... - - lint: - name: lint - if: github.event_name == 'pull_request' - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Install toolchain from mise.toml - uses: jdx/mise-action@v4 - - - name: golangci-lint - run: golangci-lint run ./... + - uses: actions/checkout@v7 + with: + ref: ${{ needs.lint.outputs.sha }} + - uses: jdx/mise-action@v4 + with: + cache: true + - uses: actions/cache@v6 + with: + path: | + ~/go/pkg/mod + ~/.cache/go-build + key: ${{ runner.os }}-go-${{ hashFiles('mise.toml', 'go.sum') }} + restore-keys: ${{ runner.os }}-go- + - run: task check:versions build vet test test:scripts diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index d2033a7..3e7d28a 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -6,71 +6,46 @@ on: workflow_dispatch: permissions: - contents: write - actions: write + contents: read + +concurrency: + group: nightly + cancel-in-progress: false jobs: nightly: + permissions: + contents: write + actions: write runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v7 with: fetch-depth: 0 + ref: main - - name: Check for new commits since the last nightly - id: check - run: | - LATEST_NIGHTLY=$(git tag -l 'v*-nightly.*' --sort=-v:refname | head -1) - if [ -z "$LATEST_NIGHTLY" ]; then - echo "No previous nightly tag, proceeding" - echo "has_changes=true" >> "$GITHUB_OUTPUT" - elif [ "$(git rev-list "${LATEST_NIGHTLY}..HEAD" --count)" -gt 0 ]; then - echo "New commits since $LATEST_NIGHTLY" - echo "has_changes=true" >> "$GITHUB_OUTPUT" - else - echo "No new commits since $LATEST_NIGHTLY, skipping" - echo "has_changes=false" >> "$GITHUB_OUTPUT" - fi - - - name: Compute next patch version - if: steps.check.outputs.has_changes == 'true' - id: version - run: | - # The manifest holds the last released version. A nightly must sort - # above it under semver, so tag the next patch: 0.6.0 -> v0.6.1-nightly.. - RELEASED=$(jq -r '.["."]' .release-please-manifest.json) - IFS=. read -r MAJOR MINOR PATCH <<< "$RELEASED" - echo "next=${MAJOR}.${MINOR}.$((PATCH + 1))" >> "$GITHUB_OUTPUT" - - - name: Create nightly tag - if: steps.check.outputs.has_changes == 'true' + - name: Create or retry nightly env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - DATE=$(date -u +%Y%m%d) - TAG="v${{ steps.version.outputs.next }}-nightly.${DATE}" - echo "Creating tag: $TAG" - git config user.name "github-actions[bot]" - git config user.email "github-actions[bot]@users.noreply.github.com" - git tag -a "$TAG" -m "Nightly build $DATE" - git push origin "$TAG" - gh workflow run prerelease.yml --ref "$TAG" + run: bash scripts/nightly.sh cleanup: + permissions: + contents: write runs-on: ubuntu-latest steps: - name: Delete nightly releases older than 7 days - uses: actions/github-script@v7 + uses: actions/github-script@v9 with: script: | const cutoff = new Date(); cutoff.setDate(cutoff.getDate() - 7); - const releases = await github.rest.repos.listReleases({ + const releases = await github.paginate(github.rest.repos.listReleases, { owner: context.repo.owner, repo: context.repo.repo, per_page: 100, }); - for (const release of releases.data) { - if (!release.tag_name.includes('-nightly.')) continue; + for (const release of releases) { + if (!/^v\d+\.\d+\.\d+-nightly\.\d{8}$/.test(release.tag_name)) continue; if (new Date(release.created_at) >= cutoff) continue; console.log(`Deleting old nightly release: ${release.tag_name}`); await github.rest.repos.deleteRelease({ @@ -81,6 +56,7 @@ jobs: owner: context.repo.owner, repo: context.repo.repo, ref: `tags/${release.tag_name}`, }); } catch (e) { + if (e.status !== 404) throw e; console.log(`Tag ${release.tag_name} already deleted`); } } diff --git a/.github/workflows/prerelease.yml b/.github/workflows/prerelease.yml index 9229d90..08729bd 100644 --- a/.github/workflows/prerelease.yml +++ b/.github/workflows/prerelease.yml @@ -10,27 +10,51 @@ on: workflow_dispatch: permissions: - contents: write + contents: read + +concurrency: + group: prerelease-${{ github.ref }} + cancel-in-progress: false jobs: + validate: + runs-on: ubuntu-latest + outputs: + sha: ${{ steps.revision.outputs.sha }} + steps: + - uses: actions/checkout@v7 + - name: Require a supported prerelease tag + run: bash scripts/validate-prerelease.sh "$GITHUB_REF" + - id: revision + run: echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" + + verify: + needs: validate + uses: ./.github/workflows/ci.yml + with: + ref: ${{ needs.validate.outputs.sha }} + goreleaser: + needs: verify + permissions: + contents: write runs-on: ubuntu-latest steps: - - name: Checkout - uses: actions/checkout@v4 + - uses: actions/checkout@v7 with: fetch-depth: 0 - - - name: Set up Go - uses: actions/setup-go@v5 + ref: ${{ needs.verify.outputs.sha }} + - uses: jdx/mise-action@v4 with: - go-version-file: go.mod - - - name: Run GoReleaser - uses: goreleaser/goreleaser-action@v6 + cache: true + - uses: actions/cache@v6 with: - distribution: goreleaser - version: "~> v2" - args: release --clean + path: | + ~/go/pkg/mod + ~/.cache/go-build + key: ${{ runner.os }}-go-${{ hashFiles('mise.toml', 'go.sum') }} + restore-keys: ${{ runner.os }}-go- + - run: task release env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GORELEASER_CURRENT_TAG: ${{ github.ref_name }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 75a41a2..1cd5d7c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -5,44 +5,57 @@ on: branches: [main] permissions: - contents: write - pull-requests: write + contents: read + +concurrency: + group: release-main + cancel-in-progress: false jobs: release-please: + permissions: + contents: write + pull-requests: write runs-on: ubuntu-latest outputs: release_created: ${{ steps.release.outputs.release_created }} tag_name: ${{ steps.release.outputs.tag_name }} steps: - - uses: googleapis/release-please-action@v4 + - uses: googleapis/release-please-action@v5 id: release with: token: ${{ secrets.GITHUB_TOKEN }} config-file: release-please-config.json manifest-file: .release-please-manifest.json - goreleaser: + verify: needs: release-please - if: ${{ needs.release-please.outputs.release_created == 'true' }} + if: needs.release-please.outputs.release_created == 'true' + uses: ./.github/workflows/ci.yml + with: + ref: ${{ needs.release-please.outputs.tag_name }} + + goreleaser: + needs: [release-please, verify] + permissions: + contents: write runs-on: ubuntu-latest steps: - - name: Checkout - uses: actions/checkout@v4 + - uses: actions/checkout@v7 with: fetch-depth: 0 - ref: ${{ needs.release-please.outputs.tag_name }} - - - name: Set up Go - uses: actions/setup-go@v5 + ref: ${{ needs.verify.outputs.sha }} + - uses: jdx/mise-action@v4 with: - go-version-file: go.mod - - - name: Run GoReleaser - uses: goreleaser/goreleaser-action@v6 + cache: true + - uses: actions/cache@v6 with: - distribution: goreleaser - version: "~> v2" - args: release --clean + path: | + ~/go/pkg/mod + ~/.cache/go-build + key: ${{ runner.os }}-go-${{ hashFiles('mise.toml', 'go.sum') }} + restore-keys: ${{ runner.os }}-go- + - run: task release env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GORELEASER_CURRENT_TAG: ${{ needs.release-please.outputs.tag_name }} diff --git a/.goreleaser.yaml b/.goreleaser.yaml index b5d10d4..3d61a8c 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -8,10 +8,6 @@ version: 2 project_name: envctl -before: - hooks: - - go mod tidy - builds: - id: envctl main: ./cmd/envctl diff --git a/Makefile b/Makefile index 3abeeb7..96c5266 100644 --- a/Makefile +++ b/Makefile @@ -1,49 +1,8 @@ -.PHONY: build test lint install clean tidy fmt release-snapshot +# Compatibility entry points. Tool versions are managed by mise.toml. +.PHONY: build test test-coverage lint install clean tidy fmt check release-snapshot -# Version info -VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev") -GIT_COMMIT ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo "unknown") -BUILD_DATE ?= $(shell date -u +"%Y-%m-%dT%H:%M:%SZ") -LDFLAGS = -X github.com/sentiolabs/envctl/internal/version.Version=$(VERSION) \ - -X github.com/sentiolabs/envctl/internal/version.GitCommit=$(GIT_COMMIT) \ - -X github.com/sentiolabs/envctl/internal/version.BuildDate=$(BUILD_DATE) +# Preserve make VERSION=... GIT_COMMIT=... BUILD_DATE=... overrides. +TASK_VARS = $(foreach var,VERSION GIT_COMMIT BUILD_DATE,$(if $(filter undefined,$(origin $(var))),,$(var)="$($(var))")) -# Build the binary -build: - go build -ldflags "$(LDFLAGS)" -o bin/envctl ./cmd/envctl - -# Run tests -test: - go test -v ./... - -# Run tests with coverage -test-coverage: - go test -coverprofile=coverage.out ./... - go tool cover -html=coverage.out -o coverage.html - -# Run linter -lint: - golangci-lint run - -# Install to GOPATH/bin -install: - go install -ldflags "$(LDFLAGS)" ./cmd/envctl - -# Clean build artifacts -clean: - rm -rf bin/ dist/ coverage.out coverage.html - -# Tidy dependencies -tidy: - go mod tidy - -# Format code -fmt: - go fmt ./... - -# Run all checks -check: fmt tidy lint test - -# GoReleaser snapshot (local dry-run) -release-snapshot: - goreleaser release --snapshot --clean +build test test-coverage lint install clean tidy fmt check release-snapshot: + task $@ $(TASK_VARS) diff --git a/README.md b/README.md index 7120f91..ae52724 100644 --- a/README.md +++ b/README.md @@ -78,10 +78,19 @@ A lightweight CLI tool that enables developers to use a secrets manager as the s curl -fsSL https://raw.githubusercontent.com/sentiolabs/envctl/main/scripts/install.sh | bash ``` -This detects your platform (macOS/Linux, amd64/arm64) and installs the latest release to `/usr/local/bin` or `~/.local/bin`. +This detects your platform (macOS/Linux, amd64/arm64), verifies the release archive +against `checksums.txt`, and installs the latest stable release to writable +`/usr/local/bin` or otherwise `~/.local/bin`. It needs curl or wget, tar, and +sha256sum or shasum. Re-running it reinstalls the selected release. + +Use `bash -s -- --tag=v1.2.3` to select a release. The existing script URL, +`--force`, `--tag TAG`, `--tag=TAG`, and `TAG`/`FORCE` environment variables +remain compatible with older envctl updaters; `--force` is now redundant. ### From Source +Building from source requires Go **1.27.1** or newer. + ```bash go install github.com/sentiolabs/envctl/cmd/envctl@latest ``` @@ -91,10 +100,16 @@ go install github.com/sentiolabs/envctl/cmd/envctl@latest ```bash git clone https://github.com/sentiolabs/envctl.git cd envctl -make build +mise install +mise exec -- task build # Binary is at ./bin/envctl ``` +Tool versions live in `mise.toml`. With mise activated, run `task ci` for the +local verification suite and `task release-snapshot` to build all release archives. +Existing `make` targets still forward to Task, including version metadata +overrides and `make install` to `GOBIN` or `GOPATH/bin`. + ### Updating ```bash @@ -103,6 +118,19 @@ envctl self update --check # show what would be installed envctl self update -y # skip the confirmation prompt ``` +Updates use selfupdate-go v0.2.0's native `ArchiveInstaller`: download the +platform archive, verify SHA-256, and atomically replace the running executable +at its resolved path. Updates do not invoke the install script, bash, or curl. +On macOS, the installer attempts ad-hoc code signing and reports signing failures +as warnings. Package-managed locations (including Homebrew and Nix) are refused +with upgrade guidance; unwritable destinations return an error instead of +installing another copy elsewhere. + +`--check` downloads no release archives and does not replace the binary. Every +update invocation, including `--check`, may remove a stale `.new` left +by an interrupted update. Checksums detect corruption against the release's +published manifest; they are not publisher signatures. + #### Release channels `self update` follows one of three channels: @@ -118,6 +146,7 @@ envctl self channel # show the current channel envctl self channel rc # switch (asks for confirmation) envctl self channel rc -y # switch without prompting envctl self channel stable # back to releases +envctl self update --force # allow downgrade when returning from a newer prerelease ``` A newer stable release always wins. On the `rc` channel you are offered `v1.4.0` the moment it ships, even if `v1.4.0-rc.3` is what you have. @@ -163,7 +192,15 @@ git tag -a v0.9.0-rc.1 -m "v0.9.0-rc.1" git push origin v0.9.0-rc.1 ``` -The `Pre-release` workflow builds the archives and publishes a GitHub prerelease. Nightlies need no action: a scheduled workflow tags `v-nightly.` whenever `main` has new commits and removes nightlies older than seven days. +Stable and prerelease workflows verify the exact release commit with the same +lint and Linux/macOS build, vet, and test jobs used by CI before publishing +archives. Manual `Pre-release` runs must select an rc, alpha, beta, or nightly tag. +Alpha/beta releases remain publishable but are not additional update channels. + +At 06:00 UTC, the nightly workflow tags `v-nightly.YYYYMMDD` when +`main` has new commits. Same-day reruns skip complete releases or retry an +incomplete release at its original tag commit; existing tags are never moved. +Nightly releases and their tags expire after seven days. ## Quick Start diff --git a/Taskfile.yml b/Taskfile.yml new file mode 100644 index 0000000..1064bb5 --- /dev/null +++ b/Taskfile.yml @@ -0,0 +1,82 @@ +version: '3' + +vars: + VERSION: + sh: git describe --tags --always --dirty 2>/dev/null || echo dev + GIT_COMMIT: + sh: git rev-parse --short HEAD 2>/dev/null || echo unknown + BUILD_DATE: + sh: date -u +%Y-%m-%dT%H:%M:%SZ + +env: + LDFLAGS: >- + -X github.com/sentiolabs/envctl/internal/version.Version={{.VERSION}} + -X github.com/sentiolabs/envctl/internal/version.GitCommit={{.GIT_COMMIT}} + -X github.com/sentiolabs/envctl/internal/version.BuildDate={{.BUILD_DATE}} + +tasks: + default: + cmds: [task --list] + build: + desc: Build envctl with version metadata + cmds: ['go build -ldflags "$LDFLAGS" -o bin/envctl ./cmd/envctl'] + install: + desc: Install envctl to GOBIN or GOPATH/bin + cmds: ['go install -ldflags "$LDFLAGS" ./cmd/envctl'] + deps: + desc: Download Go dependencies + cmds: [go mod download] + test: + desc: Run all Go tests without cached results + cmds: [go test -count=1 ./...] + test-coverage: + cmds: + - go test -coverprofile=coverage.out ./... + - go tool cover -html=coverage.out -o coverage.html + vet: + cmds: [go vet ./...] + lint: + desc: Lint the entire Go module + cmds: [golangci-lint run ./...] + check:versions: + desc: Check module and mise Go versions agree with the active toolchain + cmds: + - | + mise_go=$(sed -nE 's/^go = "([^"]+)"/\1/p' mise.toml) + mod_go=$(awk '$1 == "go" { print $2 }' go.mod) + active_go=$(go env GOVERSION) + test "$mise_go" = "$mod_go" && test "$active_go" = "go$mod_go" || { + echo "Go versions differ: mise=$mise_go module=$mod_go active=$active_go" >&2 + exit 1 + } + test:scripts: + desc: Test the bootstrap and release automation in isolation + cmds: [bash scripts/install_test.sh, bash scripts/release_test.sh] + ci: + desc: Run local CI checks + cmds: + - task: check:versions + - task: deps + - task: lint + - task: build + - task: vet + - task: test + - task: test:scripts + fmt: + cmds: [go fmt ./...] + tidy: + cmds: [go mod tidy] + check: + cmds: + - task: fmt + - task: tidy + - task: ci + clean: + cmds: [rm -rf bin/ dist/ coverage.out coverage.html] + release:check: + cmds: [goreleaser check] + release: + cmds: [goreleaser release --clean] + release-snapshot: + desc: Build all release archives without publishing + cmds: [goreleaser release --snapshot --clean] diff --git a/go.mod b/go.mod index a0184d7..2fe47e4 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/sentiolabs/envctl -go 1.27.0 +go 1.27.1 require ( github.com/aws/aws-sdk-go-v2 v1.41.1 @@ -11,7 +11,7 @@ require ( github.com/charmbracelet/bubbletea v1.3.10 github.com/charmbracelet/lipgloss v1.1.0 github.com/charmbracelet/x/exp/golden v0.0.0-20260316093931-f2fb44ab3145 - github.com/sentiolabs/go-selfupdate v0.1.1 + github.com/sentiolabs/selfupdate-go v0.2.0 github.com/spf13/cobra v1.10.2 github.com/stretchr/testify v1.11.1 github.com/zalando/go-keyring v0.2.6 diff --git a/go.sum b/go.sum index 720802f..4908a2f 100644 --- a/go.sum +++ b/go.sum @@ -94,8 +94,8 @@ github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUc github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/sahilm/fuzzy v0.1.1 h1:ceu5RHF8DGgoi+/dR5PsECjCDH1BE3Fnmpo7aVXOdRA= github.com/sahilm/fuzzy v0.1.1/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y= -github.com/sentiolabs/go-selfupdate v0.1.1 h1:76DV5ZJyldwHtDUWD1AMH145QTNOMB7OXzrfq+RIm3E= -github.com/sentiolabs/go-selfupdate v0.1.1/go.mod h1:EWIEmMHrf3qT8mxGo4GkZSlSNvbCrAdPWDthNrgvCiA= +github.com/sentiolabs/selfupdate-go v0.2.0 h1:zh+760Kw2+mxjYI4KSK3Pp20mFb3ivnh1TtM6z5w6aA= +github.com/sentiolabs/selfupdate-go v0.2.0/go.mod h1:j9hPo8QlYVPi8WSpOhh7XdtRhYWMIKdayyp26iNf/1Y= github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY= diff --git a/internal/cmd/self.go b/internal/cmd/self.go index 78626ff..c3f4510 100644 --- a/internal/cmd/self.go +++ b/internal/cmd/self.go @@ -1,18 +1,15 @@ // Package cmd implements the CLI commands for envctl. -// This file wires the self command group (update, channel) to go-selfupdate. +// This file wires the self command group (update, channel) to selfupdate-go. package cmd import ( "github.com/sentiolabs/envctl/internal/userconfig" "github.com/sentiolabs/envctl/internal/version" - "github.com/sentiolabs/go-selfupdate" - "github.com/sentiolabs/go-selfupdate/cobracmd" + "github.com/sentiolabs/selfupdate-go" + "github.com/sentiolabs/selfupdate-go/cobracmd" + "github.com/spf13/cobra" ) -// installScriptURL is the install script that self update pipes into bash -// with --force --tag=. -const installScriptURL = "https://raw.githubusercontent.com/sentiolabs/envctl/main/scripts/install.sh" - // binaryName and repoOwner identify the GitHub releases self update reads. const ( binaryName = "envctl" @@ -24,18 +21,33 @@ var selfUpdater = newSelfUpdater() // newSelfUpdater builds the updater for the envctl binary: releases come from // github.com/sentiolabs/envctl, the channel lives in the per-user config file, -// and installs run the repository's install script. +// and installs verify and replace the running executable in place. func newSelfUpdater() *selfupdate.Updater { return &selfupdate.Updater{ Name: binaryName, Version: version.Version, Source: &selfupdate.GitHubSource{Owner: repoOwner, Repo: binaryName}, Store: userconfig.ChannelStore(), - Installer: &selfupdate.ScriptInstaller{ScriptURL: installScriptURL}, + Installer: &selfupdate.ArchiveInstaller{Name: binaryName}, } } func init() { // --check has no shorthand: the root command owns -c for --config. - rootCmd.AddCommand(cobracmd.New(selfUpdater)) + rootCmd.AddCommand(newSelfCommand(selfUpdater)) +} + +// newSelfCommand binds native download progress to the same stream as Cobra. +func newSelfCommand(u *selfupdate.Updater) *cobra.Command { + command := cobracmd.New(u) + update, _, _ := command.Find([]string{"update"}) + update.PreRun = func(cmd *cobra.Command, _ []string) { + if installer, ok := u.Installer.(*selfupdate.ArchiveInstaller); ok { + installer.Out = cmd.OutOrStdout() + if u.Out != nil { + installer.Out = u.Out + } + } + } + return command } diff --git a/internal/cmd/self_archive_test.go b/internal/cmd/self_archive_test.go new file mode 100644 index 0000000..606b4f3 --- /dev/null +++ b/internal/cmd/self_archive_test.go @@ -0,0 +1,293 @@ +//nolint:testpackage // Exercises envctl's command wiring with a real native installer. +package cmd + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "testing" + + "github.com/sentiolabs/selfupdate-go" + "github.com/spf13/cobra" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const archiveTestTag = "v9.0.0" + +// testArchive builds the same single-binary tarball shape as GoReleaser. +func testArchive(t *testing.T, content []byte) []byte { + t.Helper() + var buf bytes.Buffer + gz := gzip.NewWriter(&buf) + tw := tar.NewWriter(gz) + require.NoError(t, tw.WriteHeader(&tar.Header{Name: binaryName, Mode: 0o755, Size: int64(len(content))})) + _, err := tw.Write(content) + require.NoError(t, err) + require.NoError(t, tw.Close()) + require.NoError(t, gz.Close()) + return buf.Bytes() +} + +// archiveFixture serves GitHub metadata and assets entirely over localhost. +type archiveFixture struct { + archive []byte + badChecksum bool + missingAsset bool + blockDownload bool + downloaded chan struct{} +} + +func (f *archiveFixture) server(t *testing.T) *httptest.Server { + t.Helper() + asset := fmt.Sprintf("envctl_9.0.0_%s_%s.tar.gz", runtime.GOOS, runtime.GOARCH) + var baseURL string + handler := func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/repos/sentiolabs/envctl/releases/latest": + assets := []map[string]any{ + {"name": asset, "size": len(f.archive), "browser_download_url": baseURL + "/archive"}, + {"name": "checksums.txt", "browser_download_url": baseURL + "/checksums"}, + } + if f.missingAsset { + assets = assets[1:] + } + _ = json.NewEncoder(w).Encode(map[string]any{"tag_name": archiveTestTag, "assets": assets}) + case "/archive": + if f.blockDownload { + w.WriteHeader(http.StatusOK) + w.(http.Flusher).Flush() + close(f.downloaded) + <-r.Context().Done() + return + } + _, _ = w.Write(f.archive) + case "/checksums": + sum := sha256.Sum256(f.archive) + if f.badChecksum { + sum[0] ^= 0xff + } + _, _ = fmt.Fprintf(w, "%x %s\n", sum, asset) + default: + http.NotFound(w, r) + } + } + srv := httptest.NewServer(http.HandlerFunc(handler)) + baseURL = srv.URL + t.Cleanup(srv.Close) + return srv +} + +func archiveCommand(t *testing.T, target string, fixture *archiveFixture) (*cobra.Command, *bytes.Buffer) { + t.Helper() + srv := fixture.server(t) + updater := newSelfUpdater() + updater.Version = "v1.0.0" + updater.Store = &selfupdate.MemStore{} + updater.Source = &selfupdate.GitHubSource{Owner: repoOwner, Repo: binaryName, BaseURL: srv.URL} + updater.Installer = &selfupdate.ArchiveInstaller{Name: binaryName, TargetPath: target} + command := newSelfCommand(updater) + output := &bytes.Buffer{} + command.SetOut(output) + command.SetErr(output) + return command, output +} + +func TestNativeSelfUpdate(t *testing.T) { + for _, tc := range []struct { + name string + badChecksum, missingAsset, check, decline bool + }{ + {name: "success"}, + {name: "checksum", badChecksum: true}, + {name: "missing", missingAsset: true}, + {name: "check", check: true}, + {name: "decline", decline: true}, + } { + t.Run(tc.name, func(t *testing.T) { + target := filepath.Join(t.TempDir(), binaryName) + original := []byte("original executable") + replacement := []byte("replacement executable") + writeTestExecutable(t, target, original) + fixture := &archiveFixture{ + archive: testArchive(t, replacement), badChecksum: tc.badChecksum, missingAsset: tc.missingAsset, + } + command, output := archiveCommand(t, target, fixture) + args := []string{updateCmdName, "-y"} + if tc.check { + args = []string{updateCmdName, "--check"} + } + if tc.decline { + args = []string{updateCmdName} + command.SetIn(bytes.NewBufferString("n\n")) + } + command.SetArgs(args) + err := command.ExecuteContext(t.Context()) + if tc.badChecksum || tc.missingAsset { + require.Error(t, err) + } else { + require.NoError(t, err) + } + got, err := os.ReadFile(target) + require.NoError(t, err) + if tc.name == "success" { + assert.Equal(t, replacement, got) + assert.Contains(t, output.String(), "Downloading") + assert.Contains(t, output.String(), "Verified") + assert.Contains(t, output.String(), "Installed") + } else { + assert.Equal(t, original, got) + } + }) + } +} + +func writeTestExecutable(t *testing.T, target string, content []byte) { + t.Helper() + require.NoError(t, os.WriteFile(target, content, 0o600)) //nolint:gosec // target is inside t.TempDir() + require.NoError(t, os.Chmod(target, 0o755)) +} + +func TestNativeUpdateThroughSymlink(t *testing.T) { + target := filepath.Join(t.TempDir(), binaryName) + writeTestExecutable(t, target, []byte("original")) + link := filepath.Join(t.TempDir(), binaryName) + require.NoError(t, os.Symlink(target, link)) + command, _ := archiveCommand(t, link, &archiveFixture{archive: testArchive(t, []byte("replacement"))}) + command.SetArgs([]string{updateCmdName, "-y"}) + require.NoError(t, command.ExecuteContext(t.Context())) + got, err := os.ReadFile(target) + require.NoError(t, err) + assert.Equal(t, "replacement", string(got)) + info, err := os.Stat(target) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o755), info.Mode().Perm()) + info, err = os.Lstat(link) + require.NoError(t, err) + assert.NotZero(t, info.Mode()&os.ModeSymlink) +} + +func TestNativeDownloadCancellation(t *testing.T) { + target := filepath.Join(t.TempDir(), binaryName) + writeTestExecutable(t, target, []byte("original")) + fixture := &archiveFixture{ + archive: testArchive(t, []byte("replacement")), blockDownload: true, downloaded: make(chan struct{}), + } + command, _ := archiveCommand(t, target, fixture) + command.SetArgs([]string{updateCmdName, "-y"}) + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + go func() { + select { + case <-fixture.downloaded: + cancel() + case <-ctx.Done(): + } + }() + require.ErrorIs(t, command.ExecuteContext(ctx), context.Canceled) + got, err := os.ReadFile(target) + require.NoError(t, err) + assert.Equal(t, "original", string(got)) + _, err = os.Stat(target + ".new") + assert.True(t, os.IsNotExist(err)) +} + +// lifecycleInstaller records the integration contract of the new staged API. +type lifecycleInstaller struct { + calls []string + commitErr error +} + +func (i *lifecycleInstaller) Prepare(_ context.Context, _ selfupdate.Release) (selfupdate.Staged, error) { + i.calls = append(i.calls, "prepare") + return i, nil +} + +func (i *lifecycleInstaller) Commit(_ context.Context) error { + i.calls = append(i.calls, "commit") + return i.commitErr +} + +func (i *lifecycleInstaller) Close() error { + i.calls = append(i.calls, "close") + return nil +} + +func TestSelfUpdateClosesStagedInstaller(t *testing.T) { + for _, commitErr := range []error{nil, context.Canceled} { + t.Run(fmt.Sprint(commitErr), func(t *testing.T) { + fixture := &archiveFixture{} + srv := fixture.server(t) + u := newSelfUpdater() + u.Source = &selfupdate.GitHubSource{Owner: repoOwner, Repo: binaryName, BaseURL: srv.URL} + u.Store = &selfupdate.MemStore{} + installer := &lifecycleInstaller{commitErr: commitErr} + u.Installer = installer + cmd := newSelfCommand(u) + cmd.SetOut(&bytes.Buffer{}) + cmd.SetErr(&bytes.Buffer{}) + cmd.SetArgs([]string{updateCmdName, "-y"}) + err := cmd.ExecuteContext(t.Context()) + require.ErrorIs(t, err, commitErr) + assert.Equal(t, []string{"prepare", "commit", "close"}, installer.calls) + }) + } +} + +const nativeUpdateChildEnv = "ENVCTL_NATIVE_UPDATE_CHILD" + +// TestNativeUpdateChild runs in a disposable copy of this test executable. +func TestNativeUpdateChild(t *testing.T) { + if os.Getenv(nativeUpdateChildEnv) == "" { + return + } + u := newSelfUpdater() + u.Source = &selfupdate.GitHubSource{ + Owner: repoOwner, Repo: binaryName, BaseURL: os.Getenv(nativeUpdateChildEnv), + } + u.Store = &selfupdate.MemStore{} + cmd := newSelfCommand(u) + cmd.SetArgs([]string{updateCmdName, "-y"}) + require.NoError(t, cmd.ExecuteContext(t.Context())) +} + +func TestNativeUpdateRunningExecutable(t *testing.T) { + if testing.Short() { + t.Skip("builds a replacement envctl binary") + } + dir := t.TempDir() + replacement := filepath.Join(dir, "new-envctl") + build := exec.CommandContext(t.Context(), "go", "build", "-o", replacement, "-ldflags", + "-X github.com/sentiolabs/envctl/internal/version.Version="+archiveTestTag, "../../cmd/envctl") + output, err := build.CombinedOutput() + require.NoError(t, err, "%s", output) + payload, err := os.ReadFile(replacement) + require.NoError(t, err) + fixture := &archiveFixture{archive: testArchive(t, payload)} + srv := fixture.server(t) + executable, err := os.Executable() + require.NoError(t, err) + old, err := os.ReadFile(executable) + require.NoError(t, err) + target := filepath.Join(dir, binaryName) + writeTestExecutable(t, target, old) + child := exec.CommandContext(t.Context(), target, "-test.run=^TestNativeUpdateChild$") + child.Env = append(os.Environ(), nativeUpdateChildEnv+"="+srv.URL) + output, err = child.CombinedOutput() + require.NoError(t, err, "%s", output) + // The same path now runs the released CLI, rather than the test harness. + updated := exec.CommandContext(t.Context(), target, "version") + output, err = updated.CombinedOutput() + require.NoError(t, err, "%s", output) + assert.Contains(t, string(output), archiveTestTag) +} diff --git a/internal/cmd/self_test.go b/internal/cmd/self_test.go index e6bf4a9..392588c 100644 --- a/internal/cmd/self_test.go +++ b/internal/cmd/self_test.go @@ -10,7 +10,7 @@ import ( "testing" "time" - "github.com/sentiolabs/go-selfupdate" + "github.com/sentiolabs/selfupdate-go" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -33,16 +33,18 @@ func TestSelfUpdaterWiring(t *testing.T) { require.True(t, ok) assert.Equal(t, repoOwner, src.Owner) assert.Equal(t, binaryName, src.Repo) - inst, ok := u.Installer.(*selfupdate.ScriptInstaller) + inst, ok := u.Installer.(*selfupdate.ArchiveInstaller) require.True(t, ok) - assert.Equal(t, installScriptURL, inst.ScriptURL) + assert.Equal(t, binaryName, inst.Name) + assert.False(t, inst.SkipChecksum) + assert.Nil(t, inst.Managed) assert.NotNil(t, u.Store) } func TestSelfCommandTree(t *testing.T) { self, _, err := rootCmd.Find([]string{selfCmdName}) require.NoError(t, err) - update, _, err := rootCmd.Find([]string{selfCmdName, "update"}) + update, _, err := rootCmd.Find([]string{selfCmdName, updateCmdName}) require.NoError(t, err) channel, _, err := rootCmd.Find([]string{selfCmdName, "channel"}) require.NoError(t, err) @@ -95,7 +97,7 @@ func execRoot(t *testing.T, args ...string) error { func TestSelfUpdateCheck_StableChannel(t *testing.T) { out := withTestReleases(t, selfupdate.ChannelStable, "v9.0.0", nil) - require.NoError(t, execRoot(t, selfCmdName, "update", "--check")) + require.NoError(t, execRoot(t, selfCmdName, updateCmdName, "--check")) assert.Contains(t, out.String(), "Update available: v0.0.0-dev -> v9.0.0 (stable channel)") } @@ -105,7 +107,7 @@ func TestSelfUpdateCheck_RCChannelPrefersRC(t *testing.T) { {tagNameKey: "v9.0.0", prereleaseKey: false}, } out := withTestReleases(t, selfupdate.ChannelRC, "v9.0.0", list) - require.NoError(t, execRoot(t, selfCmdName, "update", "--check")) + require.NoError(t, execRoot(t, selfCmdName, updateCmdName, "--check")) assert.Contains(t, out.String(), "v9.1.0-rc.1 (rc channel)") } @@ -115,7 +117,7 @@ func TestSelfUpdateCheck_RCChannelStableNewerWins(t *testing.T) { {tagNameKey: "v9.1.0-rc.1", prereleaseKey: true}, } out := withTestReleases(t, selfupdate.ChannelRC, "v9.2.0", list) - require.NoError(t, execRoot(t, selfCmdName, "update", "--check")) + require.NoError(t, execRoot(t, selfCmdName, updateCmdName, "--check")) assert.Contains(t, out.String(), "-> v9.2.0 (rc channel)") } @@ -135,15 +137,15 @@ func TestSelfChannelShowAndSwitch(t *testing.T) { assert.Contains(t, err.Error(), "invalid channel") } -// blockingInstaller stands in for ScriptInstaller. It reports that it +// blockingInstaller stands in for ArchiveInstaller. It reports that it // started and then returns only once its context is done, so an installer // handed a context with a nil Done channel would block forever. type blockingInstaller struct{ started chan struct{} } -func (b *blockingInstaller) Install(ctx context.Context, _ string) error { +func (b *blockingInstaller) Prepare(ctx context.Context, _ selfupdate.Release) (selfupdate.Staged, error) { close(b.started) <-ctx.Done() - return ctx.Err() + return nil, ctx.Err() } // TestSelfUpdateCancelsWithRootContext checks that the command context @@ -192,3 +194,14 @@ func TestSelfUpdateCancelsWithRootContext(t *testing.T) { t.Fatal("self update did not return after its context was cancelled") } } + +func TestSelfUpdateCheck_NightlyTag(t *testing.T) { + const nightlyTag = "v9.0.1-nightly.20260909" + list := []map[string]any{ + {tagNameKey: nightlyTag, prereleaseKey: true}, + {tagNameKey: "v9.0.0", prereleaseKey: false}, + } + out := withTestReleases(t, selfupdate.ChannelNightly, "v9.0.0", list) + require.NoError(t, execRoot(t, selfCmdName, updateCmdName, "--check")) + assert.Contains(t, out.String(), nightlyTag+" (nightly channel)") +} diff --git a/internal/userconfig/userconfig.go b/internal/userconfig/userconfig.go index 7983c1f..8d4870a 100644 --- a/internal/userconfig/userconfig.go +++ b/internal/userconfig/userconfig.go @@ -9,7 +9,7 @@ import ( "os" "path/filepath" - "github.com/sentiolabs/go-selfupdate" + "github.com/sentiolabs/selfupdate-go" "gopkg.in/yaml.v3" ) diff --git a/internal/userconfig/userconfig_test.go b/internal/userconfig/userconfig_test.go index 6327deb..4ef0125 100644 --- a/internal/userconfig/userconfig_test.go +++ b/internal/userconfig/userconfig_test.go @@ -6,7 +6,7 @@ import ( "testing" "github.com/sentiolabs/envctl/internal/userconfig" - "github.com/sentiolabs/go-selfupdate" + "github.com/sentiolabs/selfupdate-go" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/mise.toml b/mise.toml index 83d2f46..7366686 100644 --- a/mise.toml +++ b/mise.toml @@ -1,3 +1,5 @@ [tools] -go = "1.27.0" +go = "1.27.1" golangci-lint = "2.13.2" +task = "3" +goreleaser = "2.17.1" diff --git a/scripts/install.sh b/scripts/install.sh index 9b18bb0..d205fc7 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -1,411 +1,118 @@ #!/usr/bin/env bash -# -# envctl installation script -# Usage: curl -fsSL https://raw.githubusercontent.com/sentiolabs/envctl/main/scripts/install.sh | bash -# -# Options: -# --force Force reinstall even if already up-to-date -# - -set -e - -# ============ Configuration ============ +# Bootstrap envctl. Subsequent updates use: envctl self update +# curl -fsSL https://raw.githubusercontent.com/sentiolabs/envctl/main/scripts/install.sh | bash +set -euo pipefail REPO="sentiolabs/envctl" -BINARY_NAME="envctl" -FORCE="${FORCE:-false}" TAG="${TAG:-}" +# --force and FORCE are accepted for older envctl self updaters. Bootstrap +# always installs the requested release; version selection belongs to the CLI. -# ============ Output Formatting ============ - -# Detect terminal capabilities -if [[ -t 1 ]] && command -v tput &> /dev/null && [[ $(tput colors 2>/dev/null || echo 0) -ge 8 ]]; then - RED='\033[0;31m' - GREEN='\033[0;32m' - YELLOW='\033[1;33m' - BLUE='\033[0;34m' - BOLD='\033[1m' - DIM='\033[2m' - NC='\033[0m' -else - RED='' - GREEN='' - YELLOW='' - BLUE='' - BOLD='' - DIM='' - NC='' -fi - -log_info() { - echo -e "${BLUE}→${NC} $1" -} - -log_success() { - echo -e "${GREEN}✓${NC} $1" -} - -log_warning() { - echo -e "${YELLOW}!${NC} $1" -} - -log_error() { - echo -e "${RED}✗${NC} $1" >&2 -} - -log_step() { - echo -e "${DIM} $1${NC}" -} - -# ============ Version Detection ============ +fail() { printf 'envctl: %s\n' "$*" >&2; exit 1; } -# Get installed envctl version -get_installed_version() { - if command -v envctl &> /dev/null; then - local version_output - version_output=$(envctl version 2>/dev/null || echo "") - echo "$version_output" | head -1 | grep -oE 'v?[0-9]+\.[0-9]+\.[0-9]+' | head -1 || true - fi +usage() { + printf '%s\n' 'Usage: install.sh [--tag TAG|--tag=TAG] [--force]' \ + 'Install the latest stable release, or the given tag.' \ + 'Use envctl self update for subsequent updates.' } -# Normalize version strings for comparison (remove 'v' prefix) -normalize_version() { - echo "$1" | sed 's/^v//' -} - -# Compare versions: returns 0 if equal, 1 if first > second, 2 if first < second -compare_versions() { - local v1 v2 - v1=$(normalize_version "$1") - v2=$(normalize_version "$2") - - if [[ "$v1" == "$v2" ]]; then - return 0 - fi - - # Use sort -V for version comparison if available - if printf '%s\n%s' "$v1" "$v2" | sort -V -C 2>/dev/null; then - return 2 # v1 < v2 +# Write to a file so a failed download cannot feed partial data into extraction. +download() { + if command -v curl >/dev/null 2>&1; then + curl -fsSL --connect-timeout 30 --retry 2 -o "$2" "$1" + elif command -v wget >/dev/null 2>&1; then + wget -q --timeout=30 -O "$2" "$1" else - return 1 # v1 > v2 + fail 'curl or wget is required' fi } -# ============ Platform Detection ============ - -detect_platform() { - local os arch - - case "$(uname -s)" in - Darwin) - os="darwin" - ;; - Linux) - os="linux" - ;; - *) - log_error "Unsupported operating system: $(uname -s)" - exit 1 - ;; - esac - - case "$(uname -m)" in - x86_64|amd64) - arch="amd64" - ;; - aarch64|arm64) - arch="arm64" - ;; - *) - log_error "Unsupported architecture: $(uname -m)" - exit 1 - ;; - esac - - echo "${os}_${arch}" -} - -# ============ macOS Code Signing ============ - -resign_for_macos() { - local binary_path=$1 - - if [[ "$(uname -s)" != "Darwin" ]]; then - return 0 - fi - - if ! command -v codesign &> /dev/null; then - return 0 - fi - - log_step "Re-signing binary for macOS..." - codesign --remove-signature "$binary_path" 2>/dev/null || true - if codesign --force --sign - "$binary_path" 2>/dev/null; then - log_step "Binary signed" - fi -} - -# ============ Release Asset Check ============ - -release_has_asset() { - local release_json=$1 - local asset_name=$2 - - if echo "$release_json" | grep -Fq "\"name\": \"$asset_name\""; then - return 0 - fi - return 1 -} - -# ============ Installation ============ - -install_from_release() { - local platform=$1 - local installed_version=$2 - local tmp_dir - - tmp_dir=$(mktemp -d) - - local latest_version - local release_json - - if [[ -n "$TAG" ]]; then - # Install a specific version - latest_version="$TAG" - log_info "Installing specific version: ${latest_version}" - local tag_url="https://api.github.com/repos/${REPO}/releases/tags/${TAG}" - - if command -v curl &> /dev/null; then - release_json=$(curl -fsSL "$tag_url" 2>/dev/null) - elif command -v wget &> /dev/null; then - release_json=$(wget -qO- "$tag_url" 2>/dev/null) - else - log_error "Neither curl nor wget found" - rm -rf "$tmp_dir" - return 1 - fi - else - # Fetch latest release - log_info "Checking latest release..." - local latest_url="https://api.github.com/repos/${REPO}/releases/latest" - - if command -v curl &> /dev/null; then - release_json=$(curl -fsSL "$latest_url" 2>/dev/null) - elif command -v wget &> /dev/null; then - release_json=$(wget -qO- "$latest_url" 2>/dev/null) - else - log_error "Neither curl nor wget found" - rm -rf "$tmp_dir" - return 1 - fi - - latest_version=$(echo "$release_json" | grep '"tag_name"' | sed -E 's/.*"tag_name": "([^"]+)".*/\1/') - fi - - if [[ -z "$latest_version" ]]; then - log_error "Failed to fetch latest version" - rm -rf "$tmp_dir" - return 1 - fi - - # Version comparison (skip for specific tag installs) - if [[ -z "$TAG" ]] && [[ -n "$installed_version" ]] && [[ "$FORCE" != "true" ]]; then - if compare_versions "$installed_version" "$latest_version"; then - log_success "envctl ${installed_version} is already up to date" - rm -rf "$tmp_dir" - return 2 # Special return code: already up to date - fi - log_info "Updating envctl ${installed_version} → ${latest_version}" - else - log_info "Installing envctl ${latest_version}" - fi - - # Download - local archive_name="${BINARY_NAME}_${latest_version#v}_${platform}.tar.gz" - local download_url="https://github.com/${REPO}/releases/download/${latest_version}/${archive_name}" - - if ! release_has_asset "$release_json" "$archive_name"; then - log_error "No prebuilt binary for ${platform}" - rm -rf "$tmp_dir" - return 1 - fi - - log_info "Downloading ${archive_name}..." - cd "$tmp_dir" - - if command -v curl &> /dev/null; then - if ! curl -fsSL --progress-bar -o "$archive_name" "$download_url"; then - log_error "Download failed" - cd - > /dev/null || cd "$HOME" - rm -rf "$tmp_dir" - return 1 - fi - elif command -v wget &> /dev/null; then - if ! wget -q --show-progress -O "$archive_name" "$download_url" 2>/dev/null; then - # Fallback without progress for older wget - if ! wget -q -O "$archive_name" "$download_url"; then - log_error "Download failed" - cd - > /dev/null || cd "$HOME" - rm -rf "$tmp_dir" - return 1 - fi - fi - fi - - # Extract - log_step "Extracting..." - if ! tar -xzf "$archive_name"; then - log_error "Failed to extract archive" - cd - > /dev/null || cd "$HOME" - rm -rf "$tmp_dir" - return 1 - fi - - # Determine install location - local install_dir +install_directory() { if [[ -w /usr/local/bin ]]; then - install_dir="/usr/local/bin" + printf '%s\n' /usr/local/bin else - install_dir="$HOME/.local/bin" - mkdir -p "$install_dir" - fi - - # Install - log_step "Installing to ${install_dir}..." - if [[ -w "$install_dir" ]]; then - mv "$BINARY_NAME" "$install_dir/" - else - sudo mv "$BINARY_NAME" "$install_dir/" - fi - - resign_for_macos "$install_dir/$BINARY_NAME" - - cd - > /dev/null || cd "$HOME" - rm -rf "$tmp_dir" - - log_success "Installed envctl ${latest_version} to ${install_dir}/${BINARY_NAME}" - - # PATH warning - if [[ ":$PATH:" != *":$install_dir:"* ]]; then - echo "" - log_warning "${install_dir} is not in your PATH" - echo -e " Add to your shell profile: ${BOLD}export PATH=\"\$PATH:$install_dir\"${NC}" + printf '%s\n' "$HOME/.local/bin" fi - - return 0 } -# ============ Verification ============ - -verify_installation() { - if ! command -v envctl &> /dev/null; then - return 1 - fi - - echo "" - echo -e "${BOLD}envctl${NC} is ready!" - echo "" - envctl version 2>/dev/null || echo "envctl (development build)" - echo "" - echo "Get started:" - echo " envctl --help Show all commands" - echo " envctl init Create starter config" - echo " envctl validate Validate config and connectivity" - echo "" -} - -# ============ Help ============ - -show_help() { - echo "envctl Installer" - echo "" - echo "Usage: $0 [options]" - echo "" - echo "Options:" - echo " --force Force reinstall even if already up-to-date" - echo " --tag TAG Install a specific version (e.g., v0.2.0-rc.1)" - echo " --help Show this help message" - echo "" - echo "Examples:" - echo " curl -fsSL https://raw.githubusercontent.com/sentiolabs/envctl/main/scripts/install.sh | bash" - echo " curl -fsSL ... | bash -s -- --force" - echo " curl -fsSL ... | bash -s -- --tag=v0.2.0-rc.1" - echo "" -} - -# ============ Main ============ - main() { - # Parse arguments while [[ $# -gt 0 ]]; do case "$1" in - --force|-f) - FORCE="true" - shift - ;; --tag) - TAG="$2" - shift 2 - ;; - --tag=*) - TAG="${1#*=}" - shift - ;; - --help|-h) - show_help - exit 0 - ;; - *) - log_error "Unknown option: $1" - show_help - exit 1 - ;; + [[ $# -ge 2 && -n "$2" ]] || fail '--tag requires a value' + TAG="$2"; shift 2 ;; + --tag=*) TAG="${1#*=}"; [[ -n "$TAG" ]] || fail '--tag requires a value'; shift ;; + --force|-f) shift ;; + --help|-h) usage; return ;; + *) fail "unknown option: $1" ;; esac done - echo "" - echo -e "${BOLD}envctl Installer${NC}" - echo "" - - # Detect platform - local platform - platform=$(detect_platform) - log_step "Platform: ${platform}" - - # Check installed version - local installed_version - installed_version=$(get_installed_version) - if [[ -n "$installed_version" ]]; then - log_step "Installed: ${installed_version}" - fi + local os arch + case "$(uname -s)" in + Linux) os=linux ;; + Darwin) os=darwin ;; + *) fail 'supported operating systems are Linux and macOS' ;; + esac + case "$(uname -m)" in + x86_64|amd64) arch=amd64 ;; + aarch64|arm64) arch=arm64 ;; + *) fail 'supported architectures are amd64 and arm64' ;; + esac - # Install - local result - if install_from_release "$platform" "$installed_version"; then - verify_installation - exit 0 + bootstrap_staged='' + bootstrap_tmp_dir=$(mktemp -d) + # Cleanup paths stay available after Bash unwinds a failed function. + trap 'rm -rf "$bootstrap_tmp_dir"; if [[ -n "$bootstrap_staged" ]]; then rm -f "$bootstrap_staged"; fi' EXIT + trap 'exit 130' INT + trap 'exit 143' TERM + + if [[ -z "$TAG" ]]; then + download "https://api.github.com/repos/${REPO}/releases/latest" "$bootstrap_tmp_dir/release.json" + TAG=$(sed -nE 's/.*"tag_name"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/p' "$bootstrap_tmp_dir/release.json") + fi + [[ "$TAG" =~ ^v?[0-9]+\.[0-9]+\.[0-9]+(-[[:alnum:].-]+)?$ ]] || fail "invalid release tag: $TAG" + local archive="envctl_${TAG#v}_${os}_${arch}.tar.gz" + local base="https://github.com/${REPO}/releases/download/${TAG}" + printf 'Installing envctl %s (%s/%s)...\n' "$TAG" "$os" "$arch" + download "$base/$archive" "$bootstrap_tmp_dir/$archive" + download "$base/checksums.txt" "$bootstrap_tmp_dir/checksums.txt" + + local expected actual + expected=$(awk -v name="$archive" '$2 == name || $2 == "*" name {print $1}' "$bootstrap_tmp_dir/checksums.txt") + [[ "$expected" =~ ^[[:xdigit:]]{64}$ ]] || fail "missing or invalid checksum for $archive" + if command -v sha256sum >/dev/null 2>&1; then + actual=$(sha256sum "$bootstrap_tmp_dir/$archive") + elif command -v shasum >/dev/null 2>&1; then + actual=$(shasum -a 256 "$bootstrap_tmp_dir/$archive") else - result=$? - if [[ $result -eq 2 ]]; then - # Already up to date - exit 0 - fi + fail 'sha256sum or shasum is required' fi + [[ "${actual%% *}" == "$expected" ]] || fail "checksum mismatch for $archive" + # Extract only the binary, never unrelated archive entries or paths. + tar -xzOf "$bootstrap_tmp_dir/$archive" envctl > "$bootstrap_tmp_dir/envctl" + [[ -s "$bootstrap_tmp_dir/envctl" ]] || fail 'archive contains an empty binary' - # Installation failed - echo "" - log_error "Installation failed" - echo "" - echo "Manual installation options:" - echo "" - echo " 1. Download from https://github.com/${REPO}/releases/latest" - echo " Extract and move 'envctl' to your PATH" - echo "" - echo " 2. Build from source (requires Go 1.26+):" - echo " git clone https://github.com/${REPO}.git" - echo " cd envctl && make build" - echo "" - exit 1 + local install_dir + install_dir=$(install_directory) + mkdir -p "$install_dir" + bootstrap_staged=$(mktemp "$install_dir/.envctl.XXXXXX") + cp "$bootstrap_tmp_dir/envctl" "$bootstrap_staged" + chmod 755 "$bootstrap_staged" + if [[ "$os" == darwin ]] && command -v codesign >/dev/null 2>&1; then + codesign --force --sign - "$bootstrap_staged" 2>/dev/null || printf 'Warning: could not ad-hoc sign envctl\n' >&2 + fi + mv -f "$bootstrap_staged" "$install_dir/envctl" + bootstrap_staged='' + printf 'Installed envctl %s to %s/envctl\n' "$TAG" "$install_dir" + if [[ ":$PATH:" != *":$install_dir:"* ]]; then + printf 'Add %s to your PATH.\n' "$install_dir" + fi + printf 'For updates, run: envctl self update\n' + rm -rf "$bootstrap_tmp_dir" + trap - EXIT INT TERM } -main "$@" +if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then + main "$@" +fi diff --git a/scripts/install_test.sh b/scripts/install_test.sh new file mode 100644 index 0000000..dfed1f7 --- /dev/null +++ b/scripts/install_test.sh @@ -0,0 +1,86 @@ +#!/usr/bin/env bash +# Helpers below override functions called by the sourced production scripts. +# shellcheck disable=SC2329 +# shellcheck source-path=SCRIPTDIR +set -euo pipefail +script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +mkdir -p "$work/fixture" +printf '#!/bin/sh\nprintf "envctl v9.0.0\\n"\n' > "$work/fixture/envctl" +chmod 755 "$work/fixture/envctl" +fixture_archive=envctl_9.0.0_linux_amd64.tar.gz +tar -czf "$work/fixture/$fixture_archive" -C "$work/fixture" envctl +(cd "$work/fixture" && shasum -a 256 "$fixture_archive" > checksums.txt) +printf '{"tag_name":"v9.0.0"}\n' > "$work/fixture/release.json" + +run_install() ( + # shellcheck source=install.sh + source "$script_dir/install.sh" + install_directory() { printf '%s\n' "$work/case/bin"; } + uname() { if [[ "$1" == -s ]]; then printf '%s\n' "${TEST_OS:-Linux}"; else echo x86_64; fi; } + download() { + printf '%s\n' "$1" >> "$work/downloads" + [[ "${FAIL_DOWNLOAD:-false}" == false ]] || return 1 + local name=${1##*/} + [[ "$name" != latest ]] || name=release.json + cp "$work/fixture/$name" "$2" + } + export TMPDIR="$work/case/tmp" + mkdir -p "$TMPDIR" + main "$@" +) + +assert_clean() { + [[ -z "$(ls -A "$work/case/tmp")" ]] || { echo 'Temporary downloads leaked' >&2; exit 1; } + [[ -z "$(find "$work/case/bin" -name '.envctl.*' -print)" ]] || exit 1 +} + +run_install > "$work/output" +[[ "$("$work/case/bin/envctl")" == 'envctl v9.0.0' ]] +grep -q 'envctl self update' "$work/output" +assert_clean +for args in '--force --tag=v9.0.0' '--tag v9.0.0'; do + # Intentional splitting exercises both historical flag forms. + # shellcheck disable=SC2086 + run_install $args > /dev/null + assert_clean +done +TAG=v9.0.0 FORCE=true run_install > /dev/null +assert_clean + +printf 'original' > "$work/case/bin/envctl" +printf '%064d %s\n' 0 "$fixture_archive" > "$work/fixture/checksums.txt" +# Launch failure cases as standalone shells: calling main in an if condition +# would disable errexit inside the entire function being tested. +export work script_dir +export -f run_install +if bash -c 'run_install --tag=v9.0.0' > "$work/output" 2>&1; then exit 1; fi +grep -q 'checksum mismatch' "$work/output" +[[ "$(cat "$work/case/bin/envctl")" == original ]] +assert_clean +if TEST_OS=FreeBSD bash -c 'run_install' > "$work/output" 2>&1; then exit 1; fi +grep -q 'supported operating systems' "$work/output" +if FAIL_DOWNLOAD=true bash -c 'run_install' > "$work/output" 2>&1; then exit 1; fi +assert_clean +if bash -c 'run_install --tag' > "$work/output" 2>&1; then exit 1; fi +grep -q 'requires a value' "$work/output" + +# Exercise real download dispatch with one mock downloader on PATH at a time. +for tool in curl wget; do + mkdir -p "$work/$tool" + cat > "$work/$tool/$tool" <<'MOCK' +#!/bin/bash +while [[ $# -gt 0 ]]; do + case "$1" in + -o|-O) output=$2; shift 2 ;; + *) shift ;; + esac +done +exec /bin/cp "$work/fixture/envctl" "$output" +MOCK + chmod 755 "$work/$tool/$tool" + PATH="$work/$tool" /bin/bash -c 'source "$script_dir/install.sh"; download https://example.invalid/archive "$work/downloaded"' + cmp "$work/fixture/envctl" "$work/downloaded" +done +printf 'Bootstrap tests passed\n' diff --git a/scripts/nightly.sh b/scripts/nightly.sh new file mode 100644 index 0000000..65a3b6d --- /dev/null +++ b/scripts/nightly.sh @@ -0,0 +1,61 @@ +#!/usr/bin/env bash +set -euo pipefail + +# A release is complete only when all native updater assets are published. +# API errors are fatal; they must not be confused with a missing release. +release_complete() { + local tag=$1 response status + response=$(mktemp) + if gh api --include "repos/$GITHUB_REPOSITORY/releases/tags/$tag" > "$response"; then + # Drop HTTP headers before parsing the JSON body. + awk 'body { print } /^\r?$/ { body=1 }' "$response" | jq -e ' + .draft == false and + ([.assets[].name] as $names | all( + ["linux_amd64", "linux_arm64", "darwin_amd64", "darwin_arm64"][]; + ("envctl_" + $version + "_" + . + ".tar.gz") as $asset | + ($names | index($asset) != null) + )) and any(.assets[]; .name == "checksums.txt") + ' --arg version "${tag#v}" >/dev/null && status=0 || status=$? + [[ "$status" -le 1 ]] || status=2 + elif head -1 "$response" | grep -qE '^HTTP/[^ ]+ 404'; then + status=1 + else + status=2 + fi + rm -f "$response" + return "$status" +} + +main() { + local released major minor patch tag previous status + released=$(jq -er '.["."]' .release-please-manifest.json) + [[ "$released" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo 'Invalid release manifest version' >&2; exit 1; } + IFS=. read -r major minor patch <<< "$released" + tag="v${major}.${minor}.$((patch + 1))-nightly.$(date -u +%Y%m%d)" + if git rev-parse --verify "refs/tags/$tag" >/dev/null 2>&1; then + if release_complete "$tag"; then + echo "$tag is already published; skipping" + return + else + status=$? + [[ "$status" == 1 ]] || { echo 'Unable to check existing release' >&2; exit 1; } + fi + echo "Retrying $tag at its original commit" + else + previous=$(git tag -l 'v*-nightly.*' --sort=-v:refname | sed -n '1p') + if [[ -n "$previous" ]] && [[ "$(git rev-list "$previous..HEAD" --count)" == 0 ]]; then + echo 'No new commits since the last nightly; skipping' + return + fi + git config user.name 'github-actions[bot]' + git config user.email 'github-actions[bot]@users.noreply.github.com' + git tag -a "$tag" -m "Nightly build ${tag##*.}" + git push origin "refs/tags/$tag" + fi + # GITHUB_TOKEN pushes do not trigger another push workflow. + gh workflow run prerelease.yml --ref "$tag" +} + +if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then + main "$@" +fi diff --git a/scripts/release_test.sh b/scripts/release_test.sh new file mode 100644 index 0000000..16a1793 --- /dev/null +++ b/scripts/release_test.sh @@ -0,0 +1,78 @@ +#!/usr/bin/env bash +# Helpers below override functions called by the sourced production scripts. +# shellcheck disable=SC2329 +# shellcheck source-path=SCRIPTDIR +set -euo pipefail +script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +for tag in v1.2.3-rc.1 v1.2.3-rc10 v1.2.3-alpha.1 v1.2.3-beta2 v1.2.4-nightly.20260909; do + bash "$script_dir/validate-prerelease.sh" "refs/tags/$tag" +done +for ref in refs/heads/main refs/tags/v1.2.3 refs/tags/v1.2.4-nightly.202609091200 refs/heads/v1.2.3-rc.1; do + if bash "$script_dir/validate-prerelease.sh" "$ref" 2>/dev/null; then exit 1; fi +done + +# shellcheck source=nightly.sh +source "$script_dir/nightly.sh" +export GITHUB_REPOSITORY=sentiolabs/envctl +export GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null +export work +mock_status=missing +gh() { + if [[ "$1" == api ]]; then + case "$mock_status" in + error) printf 'HTTP/2.0 500 Server Error\r\n\r\n{}\n'; return 1 ;; + missing) printf 'HTTP/2.0 404 Not Found\r\n\r\n{}\n'; return 1 ;; + *) + printf 'HTTP/2.0 200 OK\r\n\r\n' + cat "$work/release.json" ;; + esac + else + printf '%s\n' "$*" >> "$work/dispatches" + fi +} +date() { echo 20260909; } +# All git writes are confined to disposable repositories. +git init -q --bare "$work/remote.git" +git init -q -b main "$work/repo" +cd "$work/repo" +git config user.name Test +git config user.email test@example.invalid +printf '{".":"1.2.3"}\n' > .release-please-manifest.json +git add .release-please-manifest.json +git commit -qm initial +git remote add origin "$work/remote.git" +main > /dev/null +tag=v1.2.4-nightly.20260909 +original=$(git rev-parse "$tag^{commit}") +grep -q "workflow run prerelease.yml --ref $tag" "$work/dispatches" +# A missing release must retry even after main advances, without moving the tag. +git commit -qm later --allow-empty +main > /dev/null +[[ "$(git rev-parse "$tag^{commit}")" == "$original" ]] +[[ "$(wc -l < "$work/dispatches" | tr -d ' ')" == 2 ]] + +jq -n --arg version "${tag#v}" ' + {draft: false, assets: ( + ["linux_amd64", "linux_arm64", "darwin_amd64", "darwin_arm64"] | + map({name: ("envctl_" + $version + "_" + . + ".tar.gz")}) + )} | .assets += [{name: "checksums.txt"}] +' > "$work/release.json" +mock_status=complete +release_complete "$tag" +main > /dev/null +[[ "$(wc -l < "$work/dispatches" | tr -d ' ')" == 2 ]] +# Partial publication is retried. +printf '{"draft":false,"assets":[]}\n' > "$work/release.json" +main > /dev/null +[[ "$(wc -l < "$work/dispatches" | tr -d ' ')" == 3 ]] +mock_status=error +if release_complete "$tag"; then exit 1; else [[ "$?" == 2 ]]; fi +# Next day's unchanged revision produces no additional tag or dispatch. +git checkout -q "$original" +date() { echo 20260910; } +main > /dev/null +[[ "$(wc -l < "$work/dispatches" | tr -d ' ')" == 3 ]] +[[ "$(git tag | wc -l | tr -d ' ')" == 1 ]] +printf 'Release automation tests passed\n' diff --git a/scripts/validate-prerelease.sh b/scripts/validate-prerelease.sh new file mode 100644 index 0000000..80724af --- /dev/null +++ b/scripts/validate-prerelease.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +# Keep nightly tags compatible with selfupdate-go's default channel matcher. +ref=${1:-} +if [[ ! "$ref" =~ ^refs/tags/v[0-9]+\.[0-9]+\.[0-9]+-((rc|alpha|beta)\.?[0-9]+|nightly\.[0-9]{8})$ ]]; then + printf 'Expected an rc, alpha, beta, or nightly tag ref; got %s\n' "$ref" >&2 + exit 1 +fi