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.
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. The checksums file is "checksums.txt" unless the Updater names another; VersionedChecksums matches GoReleaser's default, tool_1.2.3_checksums.txt.
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 ¶
- Constants
- Variables
- func Compare(a, b string) int
- func Extract(name string, archive []byte, binary string) ([]byte, error)
- func IsNewer(latest, current string) bool
- func PackageManaged(path string) bool
- func RemoveOld(path string)
- func ReplaceExecutable(path string, binary []byte) error
- func VerifyChecksum(checksums []byte, name string, data []byte) error
- func VersionedChecksums(project string) func(rel Release) string
- type Asset
- type AssetNamer
- type GitHub
- type GitLab
- type Platform
- type Release
- type Result
- type Source
- type TokenFunc
- type Updater
Examples ¶
Constants ¶
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.
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.
const DefaultMaxDownload = 512 << 20
DefaultMaxDownload bounds the archive download when Updater.MaxDownload is zero.
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 ¶
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") )
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") // that it requires one and none was given. ErrUnauthorized = errors.New("selfupdate: unauthorized") )
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.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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).
func VersionedChecksums ¶ added in v0.4.0
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 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 ¶
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.
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.
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 ¶
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.
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.
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 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 ¶
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]. 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. 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 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
// MaxDownload bounds the archive size; zero means
// [DefaultMaxDownload].
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)
}
}
Output:
func (*Updater) AssetName ¶ added in v0.4.0
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) Install ¶ added in v0.4.0
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.
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)
}
Output: