selfupdate

package
v0.13.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 34 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. Updater.Update does all of that in one call; a command that reports what it found before it installs calls Updater.Check and then Updater.Install with the release Check returned. 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. Both return the latest stable release: a GitHub pre-release or draft, and a GitLab release whose tag has a pre-release part, are passed over.

What the checksum proves

The checksum detects a download that was corrupted, or altered on a transport or storage hop between the release and the user. On its own it does not protect against somebody who can write the release's files: the checksums file comes from the same release as the archive, so whoever can replace the one can replace the other. Without a signature, an update is as trustworthy as the account, tokens and CI jobs that may publish to the release, and the TLS connection to it.

Signatures

An Updater with a Verifier also downloads a signature of the checksums file and installs nothing unless it verifies. The key that signs stays out of the release, so writing to the release is no longer enough to ship a binary. Minisign verifies minisign signatures; a tool with another scheme implements Verifier. To sign with GoReleaser, create a key pair with "minisign -G -W" (no password, for CI), keep the secret key in a CI secret, embed the public key in the tool, and sign the checksums file:

signs:
  - artifacts: checksum
    cmd: minisign
    args: ["-S", "-s", "{{ .Env.MINISIGN_SECRET_KEY_FILE }}", "-m", "${artifact}", "-x", "${signature}"]
    signature: "${artifact}.minisig"

The checksums file names every archive, so its one signature covers them all. Verification proves who signed, not that what they signed is harmless: a signed release is as trustworthy as the place the secret key is kept.

What is extracted has to be an executable for the platform (ELF, Mach-O or PE), so a file that merely has the binary's name or size is never installed; see ExtractFor.

Naming

The archive names follow GoReleaser's name_template. DefaultAssets matches GoReleaser's default (tool_1.2.3_linux_amd64.tar.gz), TitleCaseAssets the title-case template "goreleaser init" writes (tool_Linux_x86_64.tar.gz) and VersionedAssets a common hyphenated one (tool-1.2.3-linux-amd64.tar.gz); any other template is a small AssetNamer. The checksums file is "checksums.txt" unless the Updater names another; VersionedChecksums matches GoReleaser's default, tool_1.2.3_checksums.txt.

Versions

Versions are ordered as semantic versions; see Compare. A running version that is none, such as "dev", is older than any release, and what "git describe" prints for a commit after a tag is newer than that tag. A latest release whose tag is no version is an error (ErrNoVersion) rather than "already up to date".

Package managers

A binary installed by a package or version manager (a .deb or .rpm, Homebrew, MacPorts, Nix, Snap, mise, asdf, Scoop, Chocolatey, WinGet) is that manager's to update; Updater.Update and Updater.Install refuse to touch it or anything beside it and return ErrManaged. Symbolic links are resolved first, so the file a link leads to is the one that is judged and replaced. See PackageManaged for what is recognized.

The one exception is a .deb from an APT repository that is registered on the system, such as one whose package adds the repository when it is installed. With Updater.APT set, such an executable is checked against that repository and updated from it through APT, with sudo when the process is not root, after APT.Confirm agreed to the commands it was shown.

Requests and credentials

Requests are bounded by the context they are given. A source without an HTTP client of its own also gives up on a server that does not answer within half a minute and on a download that delivers nothing for a minute; a client the caller sets is the caller's to bound.

Credentials come from a TokenFunc, which is asked again with retry set after the server rejected a token. A rate limit (ErrRateLimited) is no rejection and does not ask again. The credential is sent to the source's API origin only, never to a host a download redirects to, and never over plain http except to a loopback address. A TokenFunc 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
}

Text a server or an archive chose (a response body, a file name) reaches an error message with its control characters removed.

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 an Updater fetches when it is told no other name: the name a GoReleaser configuration gives it with checksum.name_template "checksums.txt". GoReleaser's own default name carries the version; see VersionedChecksums.

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 entry in the checksums file: it was corrupted, or altered on the
	// way from the release. The opposite does not hold; see
	// [VerifyChecksum] for what a matching checksum proves.
	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")
	// ErrRateLimited reports that the server refused the request because
	// too many were sent: a 429, or a 403 that carries a Retry-After header
	// or a rate-limit header saying that no requests remain. The credential
	// is not at fault, so the [TokenFunc] is not asked for another one, and
	// the error never matches [ErrUnauthorized].
	ErrRateLimited = errors.New("selfupdate: rate limited")
)
View Source
var ErrDeclined = errors.New("selfupdate: update declined")

ErrDeclined reports that APT.Confirm declined the update, so nothing was installed.

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: none of the right name or size, or one that is no executable for the platform.

View Source
var ErrNoVersion = errors.New("selfupdate: release tag is not a version")

ErrNoVersion reports that the latest release's tag is no version, such as "release-2" or "nightly", so nothing can tell whether it is newer than the running one.

View Source
var ErrSignature = errors.New("selfupdate: bad signature")

ErrSignature reports that the checksums file of a release carries no valid signature by a trusted key: the signature is malformed, was made with another key, or does not match the file.

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.

What "git describe" prints for a build that is not a tagged commit is a version too: "v1.2.3-5-gabc1234", five commits after v1.2.3, and "v1.2.3-dirty", built from a modified work tree, are both newer than v1.2.3 and older than the next version. Semantic versioning alone would read the suffix as a pre-release and rank such a build below its tag.

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"),
		selfupdate.Compare("v1.2.3-5-gabc1234", "v1.2.3"), // "git describe", five commits after v1.2.3
	)
}
Output:
1 -1 1

func Extract

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

Extract returns the binary for the running platform from archive; see ExtractFor.

func ExtractFor added in v0.7.0

func ExtractFor(p Platform, name string, archive []byte, binary string) ([]byte, error)

ExtractFor returns the binary for platform p from archive, a .tar.gz, .tgz or .zip file called name; the zero Platform means CurrentPlatform. It takes the regular file whose base name is binary, or binary.exe when p is Windows: the one nearest the archive's root when there are several, as a completion script in a subdirectory may carry the binary's name, and the largest of those equally near. When no file has that name it takes the largest file, as long as that is at least MinBinarySize.

The file taken has to be an executable for p: an ELF file, a Mach-O file (universal ones included) for macOS and iOS, a PE file for Windows. Anything else is refused with an error wrapping ErrNoBinary. A platform with another format (AIX, Plan 9, WebAssembly) is not checked.

Entries are only read into memory, never written to disk, so paths inside the archive cannot escape anywhere, and only the best candidate so far is kept. An archive with more than 100,000 entries, with a binary larger than 1 GiB, or one that expands to more than 4 GiB is refused.

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 lies where a package or version manager installs binaries: the system directories a .deb or .rpm fills, Homebrew's Cellar (on Linux too), MacPorts, the Nix store, Snap and Flatpak, mise and asdf, or Scoop, Chocolatey and WinGet directories on Windows. It looks at path as it is given and at what it leads to once its symbolic links are resolved, so the link Homebrew keeps in its bin directory counts like the file in the Cellar. It is the default for Updater.Managed.

It goes by the path alone and knows the usual locations only. A package that installs somewhere else, such as below /opt or, on the BSDs, in /usr/local/bin beside what the user put there, is not recognized.

func RemoveOld

func RemoveOld(path string)

RemoveOld deletes what ReplaceExecutable may leave beside the executable at path. On Windows these are the old executables it moved aside, which can be deleted once they no longer run, and the path+".old" file earlier versions of this package moved them to. On every system they are new binaries an update staged more than an hour ago and never moved in, because it was interrupted. Nothing else is touched: on Unix in particular, a path+".old" file is the user's own. It ignores every error, as the next run tries again. Updater.Update and Updater.Install call it once they know the executable may be replaced.

func ReplaceExecutable

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

ReplaceExecutable replaces the file at path with binary: the new binary is written next to it and renamed over it. On Unix that is atomic, so the path always holds a complete binary, and it is safe for a running executable. The new file keeps the old one's permission bits.

Windows cannot overwrite a running executable, so there the old one is first moved aside, to a name of its own beside it (".tool.exe.old-" and random characters), which RemoveOld deletes once that executable no longer runs. Between the two renames the path holds no file for a moment. When the new binary cannot be moved in, the old one is moved back; if that fails as well, the error says where the old executable now is.

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). Only SHA-256 digests are understood.

A match proves that data is the file the checksums file describes: it was not corrupted, and not altered on a transport or storage hop between the release and here. It proves nothing about who made the file. An Updater fetches the checksums file from the same release as the archive, so somebody who can write the release's files can replace both, and the pair verifies, unless the Updater has a Verifier that checks a signature of the checksums file.

func VersionedChecksums added in v0.4.0

func VersionedChecksums(project string) func(rel Release) string

VersionedChecksums names a release's checksums file the way GoReleaser's default checksum name_template does, as in "tool_1.2.3_checksums.txt":

{{ .ProjectName }}_{{ .Version }}_checksums.txt

Use it as Updater.ChecksumsFor.

Example
package main

import (
	"fmt"

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

func main() {
	fmt.Println(selfupdate.VersionedChecksums("tool")(selfupdate.Release{Tag: "v1.2.3"}))
}
Output:
tool_1.2.3_checksums.txt

Types

type APT added in v0.12.0

type APT struct {
	// Sources is the file that registers the repository, as a deb822
	// ".sources" or a one-line ".list" file, such as
	// "/etc/apt/sources.list.d/example.sources". It is required.
	Sources string
	// Confirm is asked before the package is installed, with the plan of
	// what will run. When it returns false, the update ends with
	// [ErrDeclined]. Nil installs without asking, for a command's --yes.
	Confirm func(ctx context.Context, plan APTPlan) (bool, error)
	// Stdin, Stdout and Stderr are given to the install command, so that
	// sudo can ask for a password and apt-get can report its progress. Nil
	// means the process's own.
	Stdin  io.Reader
	Stdout io.Writer
	Stderr io.Writer
	// contains filtered or unexported fields
}

APT updates an executable that a .deb installed while the APT repository that publishes the package is registered on the system, through APT rather than by replacing the file. Set it as Updater.APT.

It applies only on Linux, only to an executable that Updater.Managed reports as managed, only while the Sources file exists, and only when dpkg names exactly one package as the owner of the executable. Anything else is refused with ErrManaged as before: an executable a .deb installed without the repository, or another package manager's.

Where it applies, the repository is the source of releases, not Updater.Source, which is never asked: Updater.Check and Updater.Update read the latest version from the repository, so no credential for the Source is needed. The repository's index is fetched into a temporary directory without root privileges, leaving the system's package lists as they are, and the package is downloaded from it the same way; APT checks both against the repository's signing key. Only the install of the downloaded file needs root: it runs apt-get update and apt-get install with the file, so that dependencies come from all of the system's repositories, freshly fetched. Without root privileges it runs through sudo, which asks for a password on the terminal itself; the process never sees it. The release's archive, checksums file and Updater.Verifier are not used.

type APTPlan added in v0.12.0

type APTPlan struct {
	// Package is the package that owns the executable, qualified with its
	// architecture, as in "tool:amd64", when dpkg qualifies it.
	Package string
	// Installed is the version of Package that is installed.
	Installed string
	// Version is the version that will be installed.
	Version string
	// File is the downloaded package that will be installed.
	File string
	// Sudo reports whether Commands run through sudo.
	Sudo bool
	// Commands are the commands that will run, in order, each as its
	// arguments with the program first.
	Commands [][]string
}

APTPlan is what an APT update is about to do, for APT.Confirm to show.

func (APTPlan) String added in v0.12.0

func (p APTPlan) String() string

String returns the commands one per line, quoted for a POSIX shell, so that a user can read them or run them by hand.

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 DefaultAssets added in v0.7.0

func DefaultAssets(project string) AssetNamer

DefaultAssets names archives the way GoReleaser does when its configuration sets no archives.name_template, 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 }}

GoReleaser's default goes on to append the MIPS variant and a GOAMD64 level other than "v1"; a release built for those needs an AssetNamer of its own. Windows archives are named ".zip" (see Platform.ArchiveExt), which takes the usual format_overrides entry: without one GoReleaser packs a tar.gz for Windows too.

Example
package main

import (
	"fmt"

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

func main() {
	name := selfupdate.DefaultAssets("tool")(selfupdate.Release{Tag: "v1.2.3"},
		selfupdate.Platform{OS: "linux", Arch: "amd64"})
	fmt.Println(name)
}
Output:
tool_1.2.3_linux_amd64.tar.gz

func TitleCaseAssets

func TitleCaseAssets(project string) AssetNamer

TitleCaseAssets names archives by a common title-case template, the one "goreleaser init" writes into a new configuration so that the names match the output of uname, as in "tool_Linux_x86_64.tar.gz" or "tool_Windows_i386.zip". It is not GoReleaser's default, which DefaultAssets follows. The template is:

{{ .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. The credential
	// only goes to the origin of APIURL; see [TokenFunc].
	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. With a Token it has to be an https URL, or an http URL of a
	// loopback address.
	APIURL string
	// Client sends the requests. Nil means a client of this package's own
	// that gives up on a server that does not connect, finish the TLS
	// handshake or send response headers within half a minute, and on a
	// response body that delivers nothing for a minute; a whole request has
	// no time limit, as a download may take long. A Client set here is used
	// as it is: its timeouts, and the context's deadline, are the caller's
	// to set. 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. An asset whose URL is not on the origin of APIURL, as no release GitHub lists has, is requested without the credential.

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. With a Token, BaseURL has to be an https URL, or an http
	// URL of a loopback address; see [TokenFunc].
	Token TokenFunc
	// TokenHeader is the header the credential goes in; empty means
	// [HeaderPrivateToken].
	TokenHeader string
	// Client sends the requests. Nil means a client of this package's own
	// that gives up on a server that does not connect, finish the TLS
	// handshake or send response headers within half a minute, and on a
	// response body that delivers nothing for a minute; a whole request has
	// no time limit, as a download may take long. A Client set here is used
	// as it is: its timeouts, and the context's deadline, are the caller's
	// to set. 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.

GitLab has no notion of a pre-release, so the latest release is found by its tag: the highest stable version among the project's most recent releases. A tag with a pre-release part, such as "v2.0.0-rc.1", and a tag that is no version are skipped.

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. It returns the highest stable version among the project's most recent releases: it reads the releases newest first, twenty at a time, takes the highest stable version of the first page that holds one, and gives up with ErrNoRelease after a hundred releases without one.

type Minisign added in v0.10.0

type Minisign struct {
	// contains filtered or unexported fields
}

Minisign verifies signatures made with minisign (https://jedisct1.github.io/minisign/) or a tool compatible with it, such as rsign2 or the minisign packages for Go. It accepts the pre-hashed signatures minisign makes by default (algorithm "ED") and the legacy ones (algorithm "Ed"), and requires a valid trusted comment signature, as minisign does.

The zero value trusts no key. Use NewMinisign.

func NewMinisign added in v0.10.0

func NewMinisign(publicKeys ...string) (*Minisign, error)

NewMinisign returns a Minisign that trusts each of publicKeys. A key is the Base64 line minisign prints ("RWQ…") or the whole public key file, its untrusted comment line included. More than one key lets a release signed with a new key verify while the old one is being retired.

func (*Minisign) SignatureName added in v0.10.0

func (m *Minisign) SignatureName(checksums string) string

SignatureName returns checksums with ".minisig" appended, the name minisign gives a signature by default.

func (*Minisign) Verify added in v0.10.0

func (m *Minisign) Verify(message, signature []byte) error

Verify checks signature, the contents of a minisign signature file, against message. The signature has to be made by one of the trusted keys, and its trusted comment has to be signed by the same key.

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 of GoReleaser's tar.gz default with the usual zip override for Windows (format_overrides, as "goreleaser init" writes it): "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, or the one Install was given. When
	// [APT] updates the executable, its Tag is the package's version in
	// the repository, such as "1.2.3".
	Release Release
	// Asset is the archive that was installed; empty when nothing was, or
	// when APT installed the release.
	Asset string
	// Package is the Debian package that owns the executable, as
	// [APTPlan.Package] names it, when [APT] updates it, whether or not it
	// installed anything; empty otherwise.
	Package 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 or Updater.Install 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 a 403 that is no rate limit), so it can drop a cached token and ask for a fresh one. It is also called with retry true when it returned no credential and the server answered 404, as a private project does to an anonymous request; an error or an empty credential from that call leaves the 404 standing. A rate limit (see ErrRateLimited) never asks again, as the credential is not at fault. Returning an error stops the request. A nil TokenFunc sends no credential.

The credential is only ever sent to the origin (scheme, host and port) of the source's API, and never over plain http, except to a loopback address: such a request fails before it is sent.

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; what "git describe" prints for a commit after
	// a tag, such as "v1.2.3-5-gabc1234", counts as newer than that tag
	// (see [Compare]).
	Current string
	// Asset names the archive for a platform. It is required; see
	// [DefaultAssets], [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]. ChecksumsFor takes precedence.
	Checksums string
	// ChecksumsFor names the checksums file of a release, for a name that
	// changes from release to release, such as GoReleaser's default
	// "tool_1.2.3_checksums.txt" (see [VersionedChecksums]).
	ChecksumsFor func(rel Release) string
	// SkipChecksum installs the archive without verifying it, for a source
	// that publishes no checksums file. What is lost is the detection of a
	// download that was corrupted or altered on its way; the checksum never
	// proved more than that (see [VerifyChecksum]). It cannot be combined
	// with Verifier.
	SkipChecksum bool
	// Verifier, when set, requires the checksums file to carry a valid
	// signature by a trusted key, published beside it under the name
	// Verifier.SignatureName gives. The archive is then installed only when
	// it matches a checksums file the key holder signed; see [Minisign].
	Verifier Verifier
	// 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. Either way the file has to
	// be an executable for Platform; see [ExtractFor].
	Binary string
	// Executable is the file to replace; empty means the running
	// executable. Symbolic links are resolved either way, so the file a
	// link leads to is replaced, not the link.
	Executable string
	// Managed reports whether a package manager owns the executable at a
	// path, which it is given with symbolic links resolved, in which case
	// Update and Install refuse to replace it. Nil
	// means [PackageManaged]; a tool that ships no OS package and may
	// replace itself anywhere sets a function that always returns false.
	Managed func(path string) bool
	// APT, when set, updates a managed executable that a .deb installed
	// from a registered APT repository through APT, instead of refusing
	// it; the repository then also replaces Source as where the latest
	// version is read. See [APT] for when it applies. Nil refuses every
	// managed executable.
	APT *APT
	// MaxDownload bounds the archive size in bytes; zero means
	// [DefaultMaxDownload]. The archive is held in memory.
	MaxDownload int64
}

Updater replaces the running executable with the latest release, or with a release it is given.

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) AssetName added in v0.4.0

func (u *Updater) AssetName(rel Release) string

AssetName returns the name of the archive Update and Install download for rel: Asset applied to Platform, or to CurrentPlatform when Platform is the zero value. It returns "" when Asset is nil.

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. When the release's tag is no version, such as "release-2", it cannot tell: it returns the release with an error wrapping ErrNoVersion rather than report the running version as current forever. An executable that Updater.APT applies to is checked against the APT repository instead, and newer means the repository offers a version other than the installed one.

func (*Updater) Install added in v0.4.0

func (u *Updater) Install(ctx context.Context, rel Release) (Result, error)

Install installs rel whatever version is running, for a caller that checked first and reported what it found: the release installed is the one Updater.Check returned, even when a newer one was published since. 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. The archive is verified against the release's checksums file unless SkipChecksum is set; see VerifyChecksum for what that proves. With a Verifier, the checksums file has to carry a valid signature too. An executable that Updater.APT applies to is updated through APT instead, to the version of the package rel's version names.

Example

A command that says what it is about to install checks first, then installs the release it found.

package main

import (
	"context"
	"fmt"
	"os"

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

func main() {
	u := &selfupdate.Updater{
		Source:       &selfupdate.GitHub{Owner: "example", Repo: "tool"},
		Current:      "v1.0.0",
		Asset:        selfupdate.TitleCaseAssets("tool"),
		ChecksumsFor: selfupdate.VersionedChecksums("tool"),
	}
	ctx := context.Background()
	rel, newer, err := u.Check(ctx)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return
	}
	if !newer {
		fmt.Printf("already up to date (%s)\n", u.Current)
		return
	}
	fmt.Printf("updating %s -> %s (%s)...\n", u.Current, rel.Tag, u.AssetName(rel))
	result, err := u.Install(ctx, rel)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return
	}
	fmt.Printf("%s is now %s\n", result.Path, rel.Tag)
}

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 it asks for the latest release it makes sure the executable may be replaced, as Install does. A latest release whose tag is no version is an error wrapping ErrNoVersion, with force too; Updater.Install installs such a release.

type Verifier added in v0.10.0

type Verifier interface {
	// SignatureName names the signature file of the checksums file called
	// checksums, as it is published beside it in the release.
	SignatureName(checksums string) string
	// Verify returns nil when signature is a valid signature of message
	// by a trusted key, and an error wrapping [ErrSignature] otherwise.
	Verify(message, signature []byte) error
}

Verifier checks the signature of a release's checksums file. Set one as Updater.Verifier to install only what a trusted key signed; see Minisign.

Jump to

Keyboard shortcuts

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