selfupdate

package
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 11, 2026 License: MIT Imports: 24 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package selfupdate replaces a running command-line tool with its latest release.

An Updater asks a Source for the latest release, downloads the archive built for the running platform, verifies it against the release's checksums file, extracts the binary and swaps it in for the running executable. Two sources are included: GitLab, which reads releases from a GitLab project and downloads from its Generic Package Registry (the one GitLab download path that honors an API token rather than a browser session), and GitHub, which reads GitHub Releases.

The archive names follow GoReleaser's name_template. TitleCaseAssets matches GoReleaser's default template (tool_Linux_x86_64.tar.gz) and VersionedAssets the common versioned one (tool-1.2.3-linux-amd64.tar.gz); any other template is a small AssetNamer.

A binary installed by a package manager (Homebrew, a .deb or .rpm, Nix, Scoop) is that manager's to update; Updater.Update refuses to touch it and returns ErrManaged.

Credentials come from a TokenFunc, which is asked again with retry set after the server rejected a token. It fits a secret.Resolver from this module:

var from secret.Source
token := func(ctx context.Context, retry bool) (string, error) {
	if retry {
		if err := resolver.Forget(from); err != nil {
			return "", err
		}
	}
	value, source, err := resolver.Resolve()
	from = source
	return value, err
}

Index

Examples

Constants

View Source
const (
	// HeaderPrivateToken carries a personal, project or group access token.
	HeaderPrivateToken = "PRIVATE-TOKEN"
	// HeaderJobToken carries a CI/CD job token ($CI_JOB_TOKEN).
	HeaderJobToken = "JOB-TOKEN"
	// HeaderDeployToken carries a deploy token with read_package_registry.
	HeaderDeployToken = "DEPLOY-TOKEN"
	// HeaderAuthorization sends the token as "Authorization: Bearer", as
	// OAuth tokens need.
	HeaderAuthorization = "Authorization"
)

Header names GitLab accepts a credential in.

View Source
const DefaultChecksums = "checksums.txt"

DefaultChecksums is the checksums file GoReleaser publishes by default.

View Source
const DefaultMaxDownload = 512 << 20

DefaultMaxDownload bounds the archive download when Updater.MaxDownload is zero.

View Source
const MinBinarySize = 1 << 20

MinBinarySize is the smallest file Extract accepts as the binary when it has to guess which file that is. Every Go binary is larger; README, LICENSE and completion files bundled beside it are far smaller.

Variables

View Source
var (
	// ErrChecksumMissing reports that the checksums file has no entry for
	// the downloaded archive.
	ErrChecksumMissing = errors.New("selfupdate: no checksum for archive")
	// ErrChecksumMismatch reports that the downloaded archive does not match
	// its checksum: it was corrupted or tampered with.
	ErrChecksumMismatch = errors.New("selfupdate: checksum mismatch")
)
View Source
var (
	// ErrNoRelease reports that the source has no published release.
	ErrNoRelease = errors.New("selfupdate: no release found")
	// ErrAssetNotFound reports that a release has no file of the requested
	// name.
	ErrAssetNotFound = errors.New("selfupdate: release asset not found")
	// ErrUnauthorized reports that the server rejected the credential, or
	// that it requires one and none was given.
	ErrUnauthorized = errors.New("selfupdate: unauthorized")
)
View Source
var ErrManaged = errors.New("selfupdate: executable is managed by a package manager")

ErrManaged reports that the executable belongs to a package manager, which is the one to update it.

View Source
var ErrNoBinary = errors.New("selfupdate: no binary in archive")

ErrNoBinary reports that an archive holds no file that can be the binary.

Functions

func Compare

func Compare(a, b string) int

Compare orders two version strings by semantic version precedence: -1 when a is older than b, 0 when they are equal, +1 when a is newer. A leading "v" is ignored, missing parts count as 0 ("1.2" equals "1.2.0"), and a pre-release is older than its release. A string that is no version at all ("dev", "") is older than any version; two such strings compare as text.

Example
package main

import (
	"fmt"

	"github.com/mittwald/cli-kit/selfupdate"
)

func main() {
	fmt.Println(selfupdate.Compare("v1.10.0", "v1.9.0"), selfupdate.Compare("1.0.0-rc.1", "1.0.0"))
}
Output:
1 -1

func Extract

func Extract(name string, archive []byte, binary string) ([]byte, error)

Extract returns the binary from archive, a .tar.gz, .tgz or .zip file called name. It takes the regular file whose base name is binary (binary or binary.exe) when there is one, and otherwise the largest file, as long as that is at least MinBinarySize. Entries are only read into memory, never written to disk, so paths inside the archive cannot escape anywhere.

func IsNewer

func IsNewer(latest, current string) bool

IsNewer reports whether latest is a newer version than current. A current that is no version at all, such as "dev" from a local build, counts as older than any release.

func PackageManaged

func PackageManaged(path string) bool

PackageManaged reports whether the executable at path, with symbolic links resolved, lies where a package manager installs binaries: the system directories a .deb or .rpm fills, Homebrew's Cellar, the Nix store, Snap and Flatpak, or Scoop, Chocolatey and WinGet directories on Windows. It is the default for Updater.Managed.

func RemoveOld

func RemoveOld(path string)

RemoveOld deletes the path+".old" file ReplaceExecutable leaves behind on Windows, once the old executable no longer runs. It ignores a missing file and every other error, as the next run tries again.

func ReplaceExecutable

func ReplaceExecutable(path string, binary []byte) error

ReplaceExecutable replaces the file at path with binary, atomically: the new binary is written next to it and renamed over it, so the path always holds a complete binary. Replacing a running executable this way is safe on Unix. Windows cannot overwrite a running executable, so there the old one is first renamed to path+".old", which RemoveOld deletes on a later run. The new file keeps the old one's permission bits.

func VerifyChecksum

func VerifyChecksum(checksums []byte, name string, data []byte) error

VerifyChecksum checks data, the downloaded file called name, against checksums, a file in the format sha256sum and GoReleaser write: one "<hex digest> <file name>" line per file, where the name may carry a leading "*" (binary mode).

Types

type Asset

type Asset struct {
	// Name is the file name, such as "tool_Linux_x86_64.tar.gz".
	Name string
	// URL is where the source downloads it from.
	URL string
}

Asset is one downloadable file of a release.

type AssetNamer

type AssetNamer func(rel Release, p Platform) string

AssetNamer returns the name of the archive a release carries for a platform. It mirrors the archives.name_template of the tool's GoReleaser configuration, plus the archive extension.

func TitleCaseAssets

func TitleCaseAssets(project string) AssetNamer

TitleCaseAssets names archives the way GoReleaser's default name_template does, as in "tool_Linux_x86_64.tar.gz" or "tool_Windows_i386.zip":

{{ .ProjectName }}_
{{- title .Os }}_
{{- if eq .Arch "amd64" }}x86_64
{{- else if eq .Arch "386" }}i386
{{- else }}{{ .Arch }}{{ end }}
{{- if .Arm }}v{{ .Arm }}{{ end }}

func VersionedAssets

func VersionedAssets(project string) AssetNamer

VersionedAssets names archives with the version and Go's own platform names, as in "tool-1.2.3-linux-amd64.tar.gz" or "tool-1.2.3-linux-armv7.tar.gz":

{{ .ProjectName }}-{{ .Version }}-{{ .Os }}-{{ .Arch }}
{{- with .Arm }}v{{ . }}{{ end }}
Example
package main

import (
	"fmt"

	"github.com/mittwald/cli-kit/selfupdate"
)

func main() {
	name := selfupdate.VersionedAssets("tool")(selfupdate.Release{Tag: "v1.2.3"},
		selfupdate.Platform{OS: "linux", Arch: "arm", Arm: "7"})
	fmt.Println(name)
}
Output:
tool-1.2.3-linux-armv7.tar.gz

type GitHub

type GitHub struct {
	// Owner and Repo name the repository, such as "example" and "tool".
	Owner string
	Repo  string
	// Token supplies the credential; nil sends none, which suits public
	// repositories within the unauthenticated rate limit.
	Token TokenFunc
	// APIURL is the API root; empty means https://api.github.com. Set it
	// for GitHub Enterprise Server ("https://github.example.com/api/v3") or
	// tests.
	APIURL string
	// Client sends the requests; nil means http.DefaultClient. A redirect
	// to another origin (scheme, host and port) never carries the
	// credential; the client's own CheckRedirect still applies.
	Client *http.Client
	// UserAgent identifies the requests; empty means a generic default.
	UserAgent string
}

GitHub is a Source for GitHub Releases. The latest release is the most recent one that is neither a draft nor a pre-release.

func (*GitHub) Download

func (g *GitHub) Download(ctx context.Context, rel Release, name string) (io.ReadCloser, error)

Download implements Source. It downloads through the asset's API URL, which works for private repositories too; the redirect to the storage host does not carry the credential along.

func (*GitHub) Latest

func (g *GitHub) Latest(ctx context.Context) (Release, error)

Latest implements Source.

type GitLab

type GitLab struct {
	// BaseURL is the instance, such as "https://gitlab.example.com". An URL
	// ending in "/api/v4" is taken as the API root itself.
	BaseURL string
	// Project is the project's path, such as "example/tool", or its numeric
	// ID. It is URL-encoded as the API requires; an already encoded path
	// (containing "%2F") is used as it is.
	Project string
	// Package is the Generic Package Registry package the releases are
	// published to; GoReleaser uses the project name.
	Package string
	// Token supplies the credential; nil sends none, which suits public
	// projects.
	Token TokenFunc
	// TokenHeader is the header the credential goes in; empty means
	// [HeaderPrivateToken].
	TokenHeader string
	// Client sends the requests; nil means http.DefaultClient. A redirect
	// to another origin (scheme, host and port) never carries the
	// credential; the client's own CheckRedirect still applies.
	Client *http.Client
	// UserAgent identifies the requests; empty means a generic default.
	UserAgent string
}

GitLab is a Source for a GitLab project. The latest release comes from the project's Releases API; files come from its Generic Package Registry, as GoReleaser publishes them with gitlab_urls.use_package_registry. Plain release links are not used: on many instances they only resolve through a browser session, whatever token the request carries.

func (*GitLab) Download

func (g *GitLab) Download(ctx context.Context, rel Release, name string) (io.ReadCloser, error)

Download implements Source. GoReleaser publishes a package under its {{ .Version }} (the tag without a leading "v"), so that version is tried first, then the raw tag.

func (*GitLab) Latest

func (g *GitLab) Latest(ctx context.Context) (Release, error)

Latest implements Source.

type Platform

type Platform struct {
	// OS is a GOOS value, such as "linux".
	OS string
	// Arch is a GOARCH value, such as "amd64".
	Arch string
	// Arm is the GOARM version, such as "7", for Arch "arm" only.
	Arm string
}

Platform is the operating system and architecture a binary is built for, in Go's terms.

func CurrentPlatform

func CurrentPlatform() Platform

CurrentPlatform returns the platform the running binary was built for. The GOARM version comes from the binary's build information, and defaults to "7" when it is missing.

func (Platform) ArchiveExt

func (p Platform) ArchiveExt() string

ArchiveExt returns the archive extension GoReleaser uses by default with a zip override for Windows: "zip" on Windows, "tar.gz" elsewhere.

type Release

type Release struct {
	// Tag is the release's tag, such as "v1.2.3".
	Tag string
	// Assets are the files the source lists for the release. A source that
	// derives download URLs from the asset name, such as [GitLab], leaves it
	// empty.
	Assets []Asset
}

Release is one published version of a tool.

func (Release) Version

func (r Release) Version() string

Version returns the tag without a leading "v" or "V": the value GoReleaser's {{ .Version }} template has.

type Result

type Result struct {
	// From is the version that ran before the update.
	From string
	// Release is the latest release.
	Release Release
	// Asset is the archive that was installed; empty when nothing was.
	Asset string
	// Path is the executable that was, or would have been, replaced.
	Path string
	// Updated is false when the running version was already current.
	Updated bool
}

Result describes what Updater.Update did.

type Source

type Source interface {
	// Latest returns the most recent stable release.
	Latest(ctx context.Context) (Release, error)
	// Download opens the named file of release rel. It returns an error
	// wrapping [ErrAssetNotFound] when the release has no such file. The
	// caller closes the reader.
	Download(ctx context.Context, rel Release, name string) (io.ReadCloser, error)
}

Source finds releases and downloads their files.

type TokenFunc

type TokenFunc func(ctx context.Context, retry bool) (string, error)

TokenFunc returns the credential for a request. It is called with retry false before the first request, and once more with retry true when the server rejected the credential (401 or 403), so it can drop a cached token and ask for a fresh one. Returning an error stops the request. A nil TokenFunc sends no credential.

type Updater

type Updater struct {
	// Source finds and downloads releases. It is required.
	Source Source
	// Current is the version of the running binary, usually injected at
	// build time. A value that is no version, such as "dev", counts as
	// older than any release.
	Current string
	// Asset names the archive for a platform. It is required; see
	// [TitleCaseAssets] and [VersionedAssets].
	Asset AssetNamer
	// Platform is the platform to download for; the zero value means
	// [CurrentPlatform].
	Platform Platform
	// Checksums is the release's checksums file; empty means
	// [DefaultChecksums].
	Checksums string
	// SkipChecksum installs the archive without verifying it. Only set it
	// for a source that publishes no checksums file and is trusted
	// otherwise.
	SkipChecksum bool
	// Binary is the file name of the binary inside the archive, without
	// ".exe"; empty means the running executable's own name. When no file
	// has that name, the largest file is taken.
	Binary string
	// Executable is the file to replace; empty means the running
	// executable, with symbolic links resolved.
	Executable string
	// Managed reports whether a package manager owns the executable at a
	// path, in which case Update refuses to replace it. Nil means
	// [PackageManaged].
	Managed func(path string) bool
	// MaxDownload bounds the archive size; zero means
	// [DefaultMaxDownload].
	MaxDownload int64
}

Updater updates the running executable to the latest release.

Example

A tool released with GoReleaser to a GitLab project's Generic Package Registry updates itself with a personal access token from $EXAMPLE_TOKEN.

package main

import (
	"context"
	"fmt"
	"os"

	"github.com/mittwald/cli-kit/selfupdate"
)

func main() {
	u := &selfupdate.Updater{
		Source: &selfupdate.GitLab{
			BaseURL: "https://gitlab.example.com",
			Project: "example/tool",
			Package: "tool",
			Token: func(context.Context, bool) (string, error) {
				return os.Getenv("EXAMPLE_TOKEN"), nil
			},
		},
		Current: "v1.0.0", // usually injected with -ldflags
		Asset:   selfupdate.TitleCaseAssets("tool"),
	}
	result, err := u.Update(context.Background(), false)
	switch {
	case err != nil:
		fmt.Fprintln(os.Stderr, err)
	case result.Updated:
		fmt.Printf("updated %s from %s to %s\n", result.Path, result.From, result.Release.Tag)
	default:
		fmt.Printf("already up to date (%s)\n", result.From)
	}
}

func (*Updater) Check

func (u *Updater) Check(ctx context.Context) (Release, bool, error)

Check returns the latest release and whether it is newer than Current.

func (*Updater) Update

func (u *Updater) Update(ctx context.Context, force bool) (Result, error)

Update installs the latest release unless the running version is already current; force installs it anyway. Before downloading anything it makes sure the executable may be replaced: it refuses, with an error wrapping ErrManaged, an executable a package manager owns, and fails early when the executable's directory is not writable.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL