Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ updater := &selfupdate.Updater{
rootCmd.AddCommand(cobracmd.New(updater))
```

A runnable version of this snippet lives in
[`examples/mytool`](examples/mytool/main.go). Build it with
`go build ./examples/mytool`.

That adds:

```text
Expand Down Expand Up @@ -82,6 +86,10 @@ before it replaces the running one. `PostInstall` runs after the replace.
A `PostInstall` error is returned with a note that the binary was already
updated.

A hook that needs the binary's own path must resolve `os.Executable()`
before the update starts. After the replace, the running process reports
the old inode, not the new file. `examples/mytool` shows the pattern.

```go
updater.PreInstall = func(ctx context.Context, current, latest string) error {
if semver.MajorMinor(latest) != semver.MajorMinor(current) {
Expand Down Expand Up @@ -144,6 +152,14 @@ Installer: &selfupdate.ScriptInstaller{
`Release` field. `Latest` still holds the tag.
- `Release` carries `Assets`. `Updater` gains `PostInstall`.

## Testing

`go test ./...` runs the unit suite and the end-to-end suite under
`internal/e2e`. The end-to-end suite builds `examples/mytool` twice with
different versions, serves a fake GitHub release from a local server, and
updates one build to the other as a subprocess. It needs a Go toolchain on
PATH and adds a few seconds. `go test -short ./...` skips it.

## Compatibility

Go 1.26 or later. The root package depends only on the standard library and
Expand Down
86 changes: 86 additions & 0 deletions examples/mytool/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
// Command mytool is the runnable version of the README example. It wires
// selfupdate-go with cobra, uses ArchiveInstaller with every default, and
// shows PreInstall and PostInstall hooks that report which binary is on disk.
//
// MYTOOL_GITHUB_API overrides the GitHub API base URL, for GitHub Enterprise
// or a local mock. Unset means api.github.com.
package main

import (
"context"
"fmt"
"io"
"os"
"os/exec"
"strings"

"github.com/sentiolabs/selfupdate-go"
"github.com/sentiolabs/selfupdate-go/cobracmd"
"github.com/spf13/cobra"
)

// version is set at build time: -ldflags "-X main.version=v1.0.0".
var version = "dev"

// envAPI overrides GitHubSource.BaseURL, for GitHub Enterprise or a local
// mock. Unset means api.github.com.
const envAPI = "MYTOOL_GITHUB_API"

// toolName is the name of the binary and GitHub repo.
const toolName = "mytool"

// exitStartup is the exit code when the executable path cannot be resolved.
const exitStartup = 2

// exitFailure is the exit code for general execution failures.
const exitFailure = 1

func main() {
exe, err := os.Executable()
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, toolName+": locate executable:", err)
os.Exit(exitStartup)
}
root := &cobra.Command{
Use: toolName,
Short: "Demo CLI for selfupdate-go",
Version: version,
}
root.SetVersionTemplate("{{.Version}}\n")
root.AddCommand(cobracmd.New(newUpdater(root.OutOrStdout(), exe)))
if err := root.Execute(); err != nil {
os.Exit(exitFailure)
}
}

// newUpdater mirrors the README wiring. Every ArchiveInstaller field is
// left at its default so asset selection, target resolution and the
// managed-path list are production behaviour.
func newUpdater(w io.Writer, exe string) *selfupdate.Updater {
return &selfupdate.Updater{
Name: toolName,
Version: version,
Source: &selfupdate.GitHubSource{Owner: "acme", Repo: toolName, BaseURL: os.Getenv(envAPI)},
// MemStore keeps the channel for this process only; a real CLI persists it.
Store: &selfupdate.MemStore{},
Installer: &selfupdate.ArchiveInstaller{},
PreInstall: reportHook(w, exe, "pre-install"),
PostInstall: reportHook(w, exe, "post-install"),
}
}

// reportHook returns a hook that runs exe --version and prints what the
// binary on disk reports. exe is resolved once at startup on purpose: after
// the update, os.Executable() in this process points at the replaced file's
// old inode, not the new binary.
func reportHook(w io.Writer, exe, name string) func(context.Context, string, string) error {
return func(ctx context.Context, _, _ string) error {
out, err := exec.CommandContext(ctx, exe, "--version").Output()
if err != nil {
// A failing hook aborts the update on purpose; the e2e suite relies on these lines.
return fmt.Errorf("%s: run %s --version: %w", name, exe, err)
}
_, _ = fmt.Fprintf(w, "%s: binary reports %s\n", name, strings.TrimSpace(string(out)))
return nil
}
}
5 changes: 5 additions & 0 deletions internal/e2e/doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// Package e2e drives examples/mytool as a subprocess against a local
// GitHub-shaped release server. TestMain builds the demo twice with
// different versions; the scenarios update one build to the other and
// inspect the binary on disk. Run go test -short to skip the suite.
package e2e
69 changes: 69 additions & 0 deletions internal/e2e/e2e_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package e2e_test

import (
"flag"
"fmt"
"os"
"os/exec"
"path/filepath"
"testing"
)

// Set by TestMain. Absolute paths of the two builds of examples/mytool.
var (
oldBinary string // built with version v1.0.0
newBinary string // built with version v1.1.0
)

const (
oldVersion = "v1.0.0"
newVersion = "v1.1.0"
envAPI = "MYTOOL_GITHUB_API"
)

// TestMain builds the demo twice. Under -short it builds nothing and every
// scenario skips itself through requireBinaries.
func TestMain(m *testing.M) {
flag.Parse()
if testing.Short() {
os.Exit(m.Run())
}
dir, err := os.MkdirTemp("", "selfupdate-e2e-*")
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, "e2e: temp dir:", err)
os.Exit(1)
}
oldBinary, err = buildDemo(dir, oldVersion)
if err == nil {
newBinary, err = buildDemo(dir, newVersion)
}
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, "e2e:", err)
_ = os.RemoveAll(dir)
os.Exit(1)
}
code := m.Run()
_ = os.RemoveAll(dir)
os.Exit(code)
}

// buildDemo compiles examples/mytool with version baked in and returns the
// binary path. The test's working directory is this package, so the
// relative source path resolves.
func buildDemo(dir, version string) (string, error) {
out := filepath.Join(dir, "mytool-"+version)
//nolint:gosec // version is one of the package's own oldVersion/newVersion constants, not external input
cmd := exec.Command("go", "build", "-ldflags", "-X main.version="+version, "-o", out, "../../examples/mytool")
if b, err := cmd.CombinedOutput(); err != nil {
return "", fmt.Errorf("build %s: %w\n%s", version, err, b)
}
return out, nil
}

// requireBinaries skips t under -short, when TestMain built nothing.
func requireBinaries(t *testing.T) {
t.Helper()
if oldBinary == "" {
t.Skip("e2e suite skipped in -short mode")
}
}
Loading
Loading