updater

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 21, 2026 License: MIT Imports: 26 Imported by: ? 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.

README

go-updater

Self-updater for Go desktop apps that ship on GitHub Releases. It detects how the app was installed (Windows installer, macOS bundle, Linux tarball, AppImage or deb/rpm/arch package), downloads the matching asset, verifies its sha256 against the release's checksums.txt, installs it and relaunches. Only net/http, hashicorp/go-version and minio/selfupdate underneath.

go get github.com/paradoxe35/go-updater

Quick start

u, err := updater.New(updater.Config{
    Owner:   "paradoxe35",
    Repo:    "myscript",
    Version: "v1.2.3", // the running version
})

rel, found, err := u.Check(ctx) // found is false when already current
if found {
    err = u.Update(ctx, rel, updater.WithProgress(func(p updater.Progress) {
        fmt.Println(p.Stage, p.Downloaded, p.Total)
    }))
    // Update relaunches the app and never returns on success.
}

Optional Config fields: AssetPrefix (default Repo), Token, AllowPrerelease, HTTPClient, Logger (*slog.Logger, discarded by default).

Release layout

Each release must carry the asset for every platform you support, named <prefix>-<os>-<arch><ext>, plus a checksums.txt in sha256sum format that lists them:

Install kind Asset
Windows (NSIS or similar installer) myapp-windows-amd64-installer.exe
macOS bundle (ditto -c -k --keepParent MyApp.app) myapp-darwin-arm64.zip, myapp-darwin-amd64.zip
Linux tarball (the executable inside) myapp-linux-amd64.tar.gz
Linux AppImage myapp-linux-amd64.AppImage
Debian/Ubuntu package myapp-linux-amd64.deb
Fedora/openSUSE package myapp-linux-amd64.rpm
Arch package myapp-linux-amd64.pkg.tar.zst
Checksums checksums.txt
sha256sum myapp-* > checksums.txt

Check never announces a release that lacks the asset for the running install, and a release without a checksum for that asset is refused before anything is downloaded.

How each kind is installed:

  • Installer: the download is started (add updater.WithInstallerArgs("/S") for a silent NSIS run) and the process exits, since Windows cannot replace a running executable.
  • Bundle: the .app directory is swapped for the one in the zip, with rollback, then relaunched through open -n so it keeps its Launch Services identity.
  • Binary: the executable inside the tarball replaces the running one atomically. The install location must be writable (ErrNotWritable otherwise).
  • AppImage: the outer file named by $APPIMAGE is replaced.
  • Package: pkexec dpkg -i / rpm -U / pacman -U, so the user gets the usual polkit password prompt. A clear error is returned when polkit is missing.

Full control

Source, private repositories and tokens

Releases come from updater.GitHub by default. Pass Token for private repositories or to lift rate limits; assets are fetched through the API with Accept: application/octet-stream, which is what private repositories require. Set Source directly for GitHub Enterprise or another host entirely:

Source: updater.GitHub{Owner: "acme", Repo: "app", Token: token, BaseURL: "https://ghe.acme.com/api/v3"},

Any type with Latest(ctx, allowPrerelease) (*Release, error) and Open(ctx, asset) (io.ReadCloser, error) is a Source.

Custom asset names
AssetName: func(t updater.Target) string {
    return fmt.Sprintf("App_%s_%s%s", t.OS, t.Arch, ext(t.Kind))
},

Target carries OS, Arch, Kind (Binary, AppImage, Bundle, Installer, Package), PackageManager (deb, rpm, arch) and Path. updater.DefaultAssetName is available to fall back on. Config.Target overrides updater.DetectTarget() for tests and unusual layouts.

Custom verification
Checksums: updater.Checksums{
    File:   "SHA256SUMS", // a different sha256sum file
    Verify: func(ctx context.Context, path string, rel *updater.Release, a updater.Asset) error {
        return checkSignature(path, rel) // replaces the checksum file entirely
    },
    SkipVerify: true, // explicit, and logged at warning level on every download
},
Staged download and install

Download in the background, install when the user clicks, relaunch when state is flushed:

dl, err := u.Download(ctx, rel, updater.WithProgress(fn)) // verified file in a temp dir
defer dl.Cleanup()

err = u.Install(ctx, dl, updater.WithoutRelaunch())
saveState()
updater.Relaunch() // or Config.BeforeRelaunch and let Install relaunch

Relaunch execs the new executable with the same arguments (open -n for bundles, the outer file for AppImages) and exits the current process.

Custom install

Config.Install replaces the built-in step for every kind. The built-ins are exported so it can compose them:

Install: func(ctx context.Context, path string, t updater.Target) error {
    if t.Kind == updater.Binary {
        return installPortable(path) // your own layout
    }
    return updater.InstallBundle(ctx, path, t) // or InstallBinary, InstallAppImage, RunInstaller, InstallPackage
},
Testing with StaticSource

updater.StaticSource serves releases from memory so an update UI can be exercised without the network:

files := map[string][]byte{"myapp-linux-amd64.tar.gz": tarball}
files["checksums.txt"] = updater.Sha256Sums(files)

u, _ := updater.New(updater.Config{
    Repo:    "myapp",
    Version: "1.0.0",
    Source:  updater.StaticSource{
        Releases: []*updater.Release{{Tag: "v2.0.0", Assets: []updater.Asset{{Name: "myapp-linux-amd64.tar.gz"}, {Name: "checksums.txt"}}}},
        Files:    files,
    },
    Target:  &updater.Target{OS: "linux", Arch: "amd64", Kind: updater.Binary, Path: scratchExe},
})

See example_test.go for runnable versions.

Errors

ErrUpToDate, ErrNoAsset, ErrNoChecksums, ErrChecksumMismatch, ErrNotWritable, ErrUnsupportedTarget and ErrInvalidVersion are wrapped with context and match with errors.Is.

Licence

MIT

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

Examples

Constants

This section is empty.

Variables

View Source
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

func DefaultAssetName(prefix string, t Target) string

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

func InstallAppImage(_ context.Context, path string, target Target) error

InstallAppImage replaces the .AppImage at target.Path with the download at path. The download is already the executable; nothing is unpacked.

func InstallBinary

func InstallBinary(_ context.Context, path string, target Target) error

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

func InstallBundle(_ context.Context, path string, target Target) error

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

func InstallPackage(_ context.Context, path string, target Target) error

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

func RunInstaller(_ context.Context, path string, _ Target, args ...string) error

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

func Sha256Sums(files map[string][]byte) []byte

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.

func (*Download) Cleanup

func (d *Download) Cleanup() error

Cleanup deletes the downloaded file. Update does this itself; callers of Download must.

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.

func (GitHub) Latest

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

Latest returns the repository's latest release; with prereleases allowed it picks the highest version among the twenty most recent releases.

func (GitHub) Open

func (g GitHub) Open(ctx context.Context, asset Asset) (io.ReadCloser, error)

Open downloads an asset through the API, which also serves private repositories.

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

func WithInstallerArgs(args ...string) Option

WithInstallerArgs passes arguments to a Windows installer, such as "/S" for a silent NSIS run.

func WithProgress

func WithProgress(fn func(Progress)) Option

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.

func (*Release) Asset

func (r *Release) Asset(name string) (Asset, bool)

Asset returns the release asset called name.

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 Stage

type Stage string

Stage names the step an update is at.

const (
	Checking    Stage = "checking"
	Downloading Stage = "downloading"
	Verifying   Stage = "verifying"
	Installing  Stage = "installing"
	Relaunching Stage = "relaunching"
)

The stages of an update, in the order they are reported.

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) Latest

func (s StaticSource) Latest(_ context.Context, allowPrerelease bool) (*Release, error)

Latest returns the highest version among Releases.

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

func DetectTarget() (Target, error)

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

func New(cfg Config) (*Updater, error)

New validates cfg and fills in its defaults. It returns ErrInvalidVersion when cfg.Version does not parse.

func (*Updater) AssetName

func (u *Updater) AssetName() (string, error)

AssetName is the release asset this updater looks for.

func (*Updater) Check

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

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

func (u *Updater) Download(ctx context.Context, rel *Release, opts ...Option) (*Download, error)

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

func (u *Updater) Install(ctx context.Context, dl *Download, opts ...Option) error

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.

func (*Updater) Target

func (u *Updater) Target() (Target, error)

Target is the install this updater replaces: Config.Target, or DetectTarget run once.

func (*Updater) Update

func (u *Updater) Update(ctx context.Context, rel *Release, opts ...Option) error

Update downloads, verifies and installs rel, then relaunches the application. A nil rel runs Check first and returns ErrUpToDate when nothing is newer.

Jump to

Keyboard shortcuts

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