Documentation
¶
Overview ¶
Package updater keeps a desktop application current from its GitHub Releases.
It detects how the application was installed (Windows installer, macOS bundle, Linux tarball, AppImage or deb/rpm/arch package), picks the matching release asset, verifies its sha256 against the release's checksum file, installs it and relaunches.
The simple path is three calls:
u, err := updater.New(updater.Config{
Owner: "paradoxe35",
Repo: "myscript",
Version: "v1.2.3",
})
rel, found, err := u.Check(ctx)
if found {
err = u.Update(ctx, rel, updater.WithProgress(func(p updater.Progress) {
log.Println(p.Stage, p.Downloaded, p.Total)
}))
}
Update never returns on success: the new version is already running. Applications that download in the background and install on a click use Download, Install and Relaunch separately.
Index ¶
- Variables
- func DefaultAssetName(prefix string, t Target) string
- func InstallAppImage(_ context.Context, path string, target Target) error
- func InstallBinary(_ context.Context, path string, target Target) error
- func InstallBundle(_ context.Context, path string, target Target) error
- func InstallPackage(_ context.Context, path string, target Target) error
- func Relaunch() error
- func RunInstaller(_ context.Context, path string, _ Target, args ...string) error
- func Sha256Sums(files map[string][]byte) []byte
- type Asset
- type Checksums
- type Config
- type Download
- type GitHub
- type Kind
- type Option
- type Progress
- type Release
- type Source
- type Stage
- type StaticSource
- type Target
- type Updater
- func (u *Updater) AssetName() (string, error)
- func (u *Updater) Check(ctx context.Context) (rel *Release, found bool, err error)
- func (u *Updater) Download(ctx context.Context, rel *Release, opts ...Option) (*Download, error)
- func (u *Updater) Install(ctx context.Context, dl *Download, opts ...Option) error
- func (u *Updater) Target() (Target, error)
- func (u *Updater) Update(ctx context.Context, rel *Release, opts ...Option) error
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrUpToDate is returned by Update when it is given a nil release and no newer one exists. ErrUpToDate = errors.New("updater: already up to date") // ErrNoAsset reports a release with no download for the current target. ErrNoAsset = errors.New("updater: no asset for this target") // ErrNoChecksums reports a release that publishes no checksum for the asset. ErrNoChecksums = errors.New("updater: no checksum for the asset") // ErrChecksumMismatch reports a download whose sha256 differs from the published one. ErrChecksumMismatch = errors.New("updater: checksum mismatch") // ErrNotWritable reports an install location this process cannot replace. ErrNotWritable = errors.New("updater: install location is not writable") // ErrUnsupportedTarget reports a target the built-in install steps cannot handle. ErrUnsupportedTarget = errors.New("updater: unsupported target") // ErrInvalidVersion reports a version string that does not parse. ErrInvalidVersion = errors.New("updater: invalid version") )
Functions ¶
func DefaultAssetName ¶
DefaultAssetName is "<prefix>-<os>-<arch>" followed by "-installer.exe", ".zip", ".AppImage", ".tar.gz", or the package extension ".deb", ".rpm" or ".pkg.tar.zst".
func InstallAppImage ¶
InstallAppImage replaces the .AppImage at target.Path with the download at path. The download is already the executable; nothing is unpacked.
func InstallBinary ¶
InstallBinary replaces the executable at target.Path with the one inside the .tar.gz at path. The swap is atomic and rolled back if it half-fails.
func InstallBundle ¶
InstallBundle replaces the .app directory at target.Path with the bundle inside the zip at path, and restores the old bundle if the swap fails.
func InstallPackage ¶
InstallPackage installs the deb, rpm or arch package at path through pkexec. The package manager comes from target.PackageManager, or from the file extension.
func Relaunch ¶
func Relaunch() error
Relaunch starts a fresh copy of the application with the same arguments and exits this process. It returns only when the new copy could not be started.
func RunInstaller ¶
RunInstaller starts the installer downloaded to path with args and returns at once. Windows cannot replace a running executable, so the process must exit right after.
func Sha256Sums ¶
Sha256Sums renders files in sha256sum format, ready to serve as a checksum file from a StaticSource.
Types ¶
type Asset ¶
type Asset struct {
Name string
Size int64
// URL is where the Source fetches the asset from; its form belongs to the Source.
URL string
}
Asset is one downloadable file attached to a release.
type Checksums ¶
type Checksums struct {
// File is the release asset in sha256sum format; defaults to "checksums.txt".
File string
// Verify replaces the checksum file entirely.
Verify func(ctx context.Context, path string, rel *Release, asset Asset) error
// SkipVerify installs downloads unverified; every skipped verification is logged at warning level.
SkipVerify bool
}
Checksums says how a download is verified before it is installed.
type Config ¶
type Config struct {
// Owner and Repo name the GitHub repository that publishes releases.
Owner string
Repo string
// Version is the running version; a leading "v" is optional.
Version string
// AssetPrefix starts every default asset name; defaults to Repo.
AssetPrefix string
// Token authenticates GitHub requests; needed for private repositories and to lift rate limits.
Token string
// AllowPrerelease lets Check offer prereleases.
AllowPrerelease bool
// HTTPClient serves GitHub requests; nil selects a client with connection timeouts and no overall deadline.
HTTPClient *http.Client
// Logger receives progress and warnings; nil discards them.
Logger *slog.Logger
// Source replaces GitHub as the release provider.
Source Source
// Target overrides DetectTarget.
Target *Target
// AssetName replaces DefaultAssetName.
AssetName func(Target) string
// Checksums controls how downloads are verified.
Checksums Checksums
// Install replaces the built-in install step for every Kind.
Install func(ctx context.Context, path string, target Target) error
// BeforeRelaunch runs after a successful install, right before the process is replaced.
BeforeRelaunch func()
}
Config describes the running application and how it is released.
type Download ¶
type Download struct {
Path string
Asset Asset
Release *Release
// contains filtered or unexported fields
}
Download is a verified release asset waiting in a temporary directory.
type GitHub ¶
type GitHub struct {
Owner string
Repo string
// Token is sent as a bearer token; required for private repositories.
Token string
// BaseURL defaults to https://api.github.com; set it for GitHub Enterprise.
BaseURL string
// Client defaults to one with connection timeouts and no overall deadline.
Client *http.Client
}
GitHub is the default Source, backed by the GitHub REST API.
type Kind ¶
type Kind string
Kind is the way the application was installed, which decides the asset and the install step.
const ( // Binary is a bare executable, updated from a .tar.gz. Binary Kind = "binary" // AppImage is a Linux AppImage, updated by replacing the outer file. AppImage Kind = "appimage" // Bundle is a macOS .app, updated from a ditto zip. Bundle Kind = "bundle" // Installer is a Windows install, updated by running the new installer. Installer Kind = "installer" // Package is a Linux deb, rpm or arch install, updated through the package manager. Package Kind = "package" )
The install kinds the built-in steps handle.
type Option ¶
type Option func(*options)
Option adjusts one Update, Download or Install call.
func WithInstallerArgs ¶
WithInstallerArgs passes arguments to a Windows installer, such as "/S" for a silent NSIS run.
func WithProgress ¶
WithProgress reports each stage, and download progress, to fn.
func WithoutRelaunch ¶
func WithoutRelaunch() Option
WithoutRelaunch leaves the process running after the install; the caller quits or calls Relaunch.
type Progress ¶
type Progress struct {
Stage Stage
Downloaded int64
// Total is 0 when the asset size is unknown.
Total int64
}
Progress is one report to the WithProgress callback; Downloaded and Total are only set while Downloading.
type Release ¶
type Release struct {
// Version is the parsed Tag; a Source may leave it nil and let the updater parse Tag.
Version *version.Version
Tag string
Name string
Notes string
Prerelease bool
PublishedAt time.Time
Assets []Asset
}
Release is one published version of the application.
type Source ¶
type Source interface {
// Latest returns the newest release, skipping prereleases unless allowed.
Latest(ctx context.Context, allowPrerelease bool) (*Release, error)
// Open streams the content of asset.
Open(ctx context.Context, asset Asset) (io.ReadCloser, error)
}
Source lists releases and serves their assets.
type StaticSource ¶
type StaticSource struct {
Releases []*Release
// Files holds asset content keyed by asset name.
Files map[string][]byte
}
StaticSource serves releases from memory, for tests and update-UI development.
func (StaticSource) Open ¶
func (s StaticSource) Open(_ context.Context, asset Asset) (io.ReadCloser, error)
Open returns the content stored under asset.Name.
type Target ¶
type Target struct {
OS string
Arch string
Kind Kind
// PackageManager is "deb", "rpm" or "arch" when Kind is Package.
PackageManager string
// Path is what gets replaced: the executable, the .AppImage file or the .app directory.
Path string
}
Target is the installed application the updater replaces.
func DetectTarget ¶
DetectTarget inspects the running process: Windows is an Installer, an executable inside an .app is a Bundle, $APPIMAGE marks an AppImage, a package-owned executable is a Package, and anything else is a Binary.
type Updater ¶
type Updater struct {
// contains filtered or unexported fields
}
Updater checks for, downloads and installs releases of the running application.
func New ¶
New validates cfg and fills in its defaults. It returns ErrInvalidVersion when cfg.Version does not parse.
func (*Updater) Check ¶
Check returns the latest release when it is newer than the running version and ships an asset for this target; found is false when the application is current.
Example ¶
package main
import (
"context"
"fmt"
"os"
"path/filepath"
"github.com/paradoxe35/go-updater"
)
// demoSource publishes v2.0.0 for a fake linux/amd64 install, so the examples run
// without the network and without touching the test binary.
func demoSource(dir string) (updater.Source, *updater.Target) {
files := map[string][]byte{"demo-linux-amd64.tar.gz": []byte("not really a tarball")}
files["checksums.txt"] = updater.Sha256Sums(files)
source := updater.StaticSource{
Releases: []*updater.Release{{
Tag: "v2.0.0",
Notes: "Faster startup.",
Assets: []updater.Asset{{Name: "demo-linux-amd64.tar.gz", Size: 20}, {Name: "checksums.txt"}},
}},
Files: files,
}
exe := filepath.Join(dir, "demo")
os.WriteFile(exe, []byte("v1"), 0o755)
return source, &updater.Target{OS: "linux", Arch: "amd64", Kind: updater.Binary, Path: exe}
}
func main() {
dir, _ := os.MkdirTemp("", "example")
defer os.RemoveAll(dir)
source, target := demoSource(dir)
u, err := updater.New(updater.Config{
Owner: "paradoxe35",
Repo: "demo",
Version: "v1.0.0",
Source: source, // omit to use GitHub Releases
Target: target, // omit to detect the running install
})
if err != nil {
panic(err)
}
rel, found, err := u.Check(context.Background())
if err != nil {
panic(err)
}
if found {
fmt.Println("update available:", rel.Tag, "-", rel.Notes)
}
}
Output: update available: v2.0.0 - Faster startup.
func (*Updater) Download ¶
Download fetches the asset for this target into a temporary directory and verifies it. The caller installs it later and calls Cleanup when done.
Example ¶
package main
import (
"context"
"fmt"
"os"
"path/filepath"
"github.com/paradoxe35/go-updater"
)
// demoSource publishes v2.0.0 for a fake linux/amd64 install, so the examples run
// without the network and without touching the test binary.
func demoSource(dir string) (updater.Source, *updater.Target) {
files := map[string][]byte{"demo-linux-amd64.tar.gz": []byte("not really a tarball")}
files["checksums.txt"] = updater.Sha256Sums(files)
source := updater.StaticSource{
Releases: []*updater.Release{{
Tag: "v2.0.0",
Notes: "Faster startup.",
Assets: []updater.Asset{{Name: "demo-linux-amd64.tar.gz", Size: 20}, {Name: "checksums.txt"}},
}},
Files: files,
}
exe := filepath.Join(dir, "demo")
os.WriteFile(exe, []byte("v1"), 0o755)
return source, &updater.Target{OS: "linux", Arch: "amd64", Kind: updater.Binary, Path: exe}
}
func main() {
dir, _ := os.MkdirTemp("", "example")
defer os.RemoveAll(dir)
source, target := demoSource(dir)
u, _ := updater.New(updater.Config{
Repo: "demo",
Version: "1.0.0",
Source: source,
Target: target,
Install: func(_ context.Context, path string, t updater.Target) error {
fmt.Println("installing", filepath.Base(path), "as", t.Kind)
return nil
},
})
rel, _, _ := u.Check(context.Background())
// Download in the background, verified against checksums.txt.
dl, err := u.Download(context.Background(), rel, updater.WithProgress(func(p updater.Progress) {
if p.Stage == updater.Downloading && p.Downloaded == p.Total {
fmt.Println("downloaded", p.Downloaded, "bytes")
}
}))
if err != nil {
panic(err)
}
defer dl.Cleanup()
// Install when the user clicks; relaunch with updater.Relaunch() once state is flushed.
if err := u.Install(context.Background(), dl, updater.WithoutRelaunch()); err != nil {
panic(err)
}
}
Output: downloaded 20 bytes installing demo-linux-amd64.tar.gz as binary
func (*Updater) Install ¶
Install applies a Download to this target and relaunches the application unless WithoutRelaunch is given, in which case the caller must quit or call Relaunch. A Windows installer runs on its own; the process must exit right after Install returns.