installer

package
v0.4.9 Latest Latest
Warning

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

Go to latest
Published: Jul 24, 2026 License: MIT Imports: 30 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidSlug                 = errors.New("invalid slug format, expected 'owner/name'")
	ErrIncorrectParameterOwner     = errors.New("incorrect parameter \"owner\"")
	ErrIncorrectParameterRepo      = errors.New("incorrect parameter \"repo\"")
	ErrInvalidRelease              = errors.New("invalid release (nil argument)")
	ErrValidationAssetNotFound     = errors.New("validation file not found")
	ErrIncorrectChecksumFile       = errors.New("incorrect checksum file format")
	ErrChecksumValidationFailed    = errors.New("sha256 validation failed")
	ErrHashNotFound                = errors.New("hash not found in checksum file")
	ErrCannotDecompressFile        = errors.New("failed to decompress")
	ErrExecutableNotFoundInArchive = errors.New("executable not found")
)

Possible errors returned

Functions

func Apply

func Apply(update io.Reader, opts Options) error

Apply performs an update of the current executable (or opts.TargetFile, if set) with the contents of the given io.Reader.

Apply performs the following actions to ensure a safe cross-platform update:

1. If configured, computes the checksum of the new executable and verifies it matches.

2. If configured, verifies the signature with a public key.

3. Creates a new file, /path/to/.target.new with the TargetMode with the contents of the updated file

4. Renames /path/to/target to /path/to/.target.old

5. Renames /path/to/.target.new to /path/to/target

6. If the final rename is successful, deletes /path/to/.target.old, returns no error. On Windows, the removal of /path/to/target.old always fails, so instead Apply hides the old file instead.

7. If the final rename fails, attempts to roll back by renaming /path/to/.target.old back to /path/to/target.

If the roll back operation fails, the file system is left in an inconsistent state (between steps 5 and 6) where there is no new executable file and the old executable file could not be moved to its original location. In this case you should notify the user of the bad news and ask them to recover manually. Applications can determine whether the rollback failed by calling RollbackError, see the documentation on that function for additional detail.

func DecompressCommand

func DecompressCommand(src io.Reader, url, cmd, os, arch string) (io.Reader, error)

DecompressCommand decompresses the given source. Archive and compression format is automatically detected from 'url' parameter, which represents the URL of asset, or simply a filename (with an extension). This returns a reader for the decompressed command given by 'cmd'. '.zip', '.tar.gz', '.tar.xz', '.tgz', '.gz', '.bz2' and '.xz' are supported.

These wrapped errors can be returned:

  • ErrCannotDecompressFile
  • ErrExecutableNotFoundInArchive

func RollbackError

func RollbackError(err error) error

RollbackError takes an error value returned by Apply and returns the error, if any, that occurred when attempting to roll back from a failed update. Applications should always call this function on any non-nil errors returned by Apply.

If no rollback was needed or if the rollback was successful, RollbackError returns nil, otherwise it returns the error encountered when trying to roll back.

func SetLogger

func SetLogger(logger Logger)

SetLogger redirects all logs to the logger defined in parameter. By default logs are not sent anywhere.

Types

type ChecksumValidator

type ChecksumValidator struct {
	// UniqueFilename is the name of the global file containing all the checksums
	// Usually "checksums.txt", "SHA256SUMS", etc.
	UniqueFilename string
}

ChecksumValidator is a SHA256 checksum validator where all the validation hash are in a single file (one per line)

func (*ChecksumValidator) GetValidationAssetName

func (v *ChecksumValidator) GetValidationAssetName(_ string) string

GetValidationAssetName returns the unique asset name for SHA256 validation.

func (*ChecksumValidator) Validate

func (v *ChecksumValidator) Validate(filename string, release, asset []byte) error

Validate the SHA256 sum of the release against the contents of an additional asset file containing all the checksums (one file per line).

type Config

type Config struct {
	// Source where to load the releases from (example: GitHubSource).
	Source Source
	// Validator represents types which enable additional validation of downloaded release.
	Validator Validator
	// Filters are regexp used to filter on specific assets for releases with multiple assets.
	// An asset is selected if it matches any of those, in addition to the regular tag, os, arch, extensions.
	// Please make sure that your filter(s) uniquely match an asset.
	Filters []string
	// OS is set to the value of runtime.GOOS by default, but you can force another value here.
	OS string
	// Arch is set to the value of runtime.GOARCH by default, but you can force another value here.
	Arch string
	// Arm 32bits version. Valid values are 0 (unknown), 5, 6 or 7. Default is detected value (if available).
	Arm uint8
	// Arch name for macOS universal binary. Default to none.
	// If set, the updater will only pick the universal binary if the Arch is not found.
	UniversalArch string
	// Draft permits an upgrade to a "draft" version (default to false).
	Draft bool
	// Prerelease permits an upgrade to a "pre-release" version (default to false).
	Prerelease bool
	// To prevent automatic removal of the old binary, and allow you to test an update prior to manual removal.
	OldSavePath string
}

Config represents the configuration of self-update.

type GitHubAsset

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

func NewGitHubAsset

func NewGitHubAsset(from *github.ReleaseAsset) *GitHubAsset

func (*GitHubAsset) GetBrowserDownloadURL

func (a *GitHubAsset) GetBrowserDownloadURL() string

func (*GitHubAsset) GetID

func (a *GitHubAsset) GetID() int64

func (*GitHubAsset) GetName

func (a *GitHubAsset) GetName() string

func (*GitHubAsset) GetSize

func (a *GitHubAsset) GetSize() int

type GitHubConfig

type GitHubConfig struct {
	// APIToken represents GitHub API token. If it's not empty, it will be used for authentication of GitHub API
	APIToken string
	// EnterpriseBaseURL is a base URL of GitHub API. If you want to use this library with GitHub Enterprise,
	// please set "https://{your-organization-address}/api/v3/" to this field.
	EnterpriseBaseURL string
	// EnterpriseUploadURL is a URL to upload stuffs to GitHub Enterprise instance. This is often the same as an API base URL.
	// So if this field is not set and EnterpriseBaseURL is set, EnterpriseBaseURL is also set to this field.
	EnterpriseUploadURL string
}

GitHubConfig is an object to pass to NewGitHubSource

type GitHubRelease

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

func NewGitHubRelease

func NewGitHubRelease(from *github.RepositoryRelease) *GitHubRelease

func (*GitHubRelease) GetAssets

func (r *GitHubRelease) GetAssets() []SourceAsset

func (*GitHubRelease) GetDraft

func (r *GitHubRelease) GetDraft() bool

func (*GitHubRelease) GetID

func (r *GitHubRelease) GetID() int64

func (*GitHubRelease) GetName

func (r *GitHubRelease) GetName() string

func (*GitHubRelease) GetPrerelease

func (r *GitHubRelease) GetPrerelease() bool

func (*GitHubRelease) GetPublishedAt

func (r *GitHubRelease) GetPublishedAt() time.Time

func (*GitHubRelease) GetReleaseNotes

func (r *GitHubRelease) GetReleaseNotes() string

func (*GitHubRelease) GetTagName

func (r *GitHubRelease) GetTagName() string

func (*GitHubRelease) GetURL

func (r *GitHubRelease) GetURL() string

type GitHubSource

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

GitHubSource is used to load release information from GitHub

func NewGitHubSource

func NewGitHubSource(config GitHubConfig) (*GitHubSource, error)

NewGitHubSource creates a new GitHubSource from a config object. It initializes a GitHub API client. If you set your API token to the $GITHUB_TOKEN environment variable, the client will use it. You can pass an empty GitHubConfig{} to use the default configuration. The function will return an error if the GitHub Enterprise URLs in the config object cannot be parsed.

func (*GitHubSource) DownloadReleaseAsset

func (s *GitHubSource) DownloadReleaseAsset(
	ctx context.Context,
	rel *Release,
	assetID int64,
) (io.ReadCloser, error)

DownloadReleaseAsset downloads an asset from a release. It returns an io.ReadCloser: it is your responsibility to Close it.

func (*GitHubSource) ListReleases

func (s *GitHubSource) ListReleases(
	ctx context.Context,
	repository Repository,
) ([]SourceRelease, error)

ListReleases returns all available releases

type Logger

type Logger interface {
	// Print calls Output to print to the standard logger. Arguments are handled in the manner of fmt.Print.
	Print(v ...any)
	// Printf calls Output to print to the standard logger. Arguments are handled in the manner of fmt.Printf.
	Printf(format string, v ...any)
}

Logger interface. Compatible with standard log.Logger

type Options

type Options struct {
	// TargetPath defines the path to the file to update.
	// The empty string means 'the executable file of the running program'.
	TargetPath string

	// Create TargetPath replacement with this file mode. If zero, defaults to 0755.
	TargetMode os.FileMode

	// Checksum of the new binary to verify against. If nil, no checksum or signature verification is done.
	Checksum []byte

	// Public key to use for signature verification. If nil, no signature verification is done.
	PublicKey crypto.PublicKey

	// Signature to verify the updated file. If nil, no signature verification is done.
	Signature []byte

	// Pluggable signature verification algorithm. If nil, ECDSA is used.
	Verifier Verifier

	// Use this hash function to generate the checksum. If not set, SHA256 is used.
	Hash crypto.Hash

	// Store the old executable file at this path after a successful update.
	// The empty string means the old executable file will be removed after the update.
	OldSavePath string
}

Options for Apply update

func (*Options) SetPublicKeyPEM

func (o *Options) SetPublicKeyPEM(pembytes []byte) error

SetPublicKeyPEM is a convenience method to set the PublicKey property used for checking a completed update's signature by parsing a Public Key formatted as PEM data.

type Release

type Release struct {
	// AssetURL is a URL to the uploaded file for the release
	AssetURL string
	// AssetSize represents the size of asset in bytes
	AssetByteSize int
	// AssetID is the ID of the asset on the source platform
	AssetID int64
	// ReleaseID is the ID of the release on the source platform
	ReleaseID int64
	// AssetName is the filename of the asset
	AssetName string
	// ValidationAssetID is the ID of additional validation asset on the source platform
	ValidationAssetID int64
	// ValidationAssetURL is the URL of additional validation asset on the source platform
	ValidationAssetURL string
	// ValidationChain is the list of validation assets being used (first record is ValidationAssetID).
	ValidationChain []struct {
		// ValidationAssetID is the ID of additional validation asset on the source platform
		ValidationAssetID int64
		// ValidationAssetURL is the filename of additional validation asset on the source platform
		ValidationAssetName string
		// ValidationAssetURL is the URL of additional validation asset on the source platform
		ValidationAssetURL string
	}
	// URL is a URL to release page for browsing
	URL string
	// ReleaseNotes is a release notes of the release
	ReleaseNotes string
	// Name represents a name of the release
	Name string
	// PublishedAt is the time when the release was published
	PublishedAt time.Time
	// OS this release is for
	OS string
	// Arch this release is for
	Arch string
	// Arm 32bits version (if any). Valid values are 0 (unknown), 5, 6 or 7
	Arm uint8
	// Prerelease is set to true for alpha, beta or release candidates
	Prerelease bool
	// contains filtered or unexported fields
}

Release represents a release asset for current OS and arch.

func (Release) Version

func (r Release) Version() string

Version is the version string of the release

type Repository

type Repository interface {
	GetSlug() (string, string, error)
}

type RepositorySlug

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

func NewRepositorySlug

func NewRepositorySlug(owner, repo string) RepositorySlug

NewRepositorySlug creates a RepositorySlug from owner and repo parameters

func (RepositorySlug) GetSlug

func (r RepositorySlug) GetSlug() (string, string, error)

type SHAValidator

type SHAValidator struct{}

SHAValidator specifies a SHA256 validator for additional file validation before updating.

func (*SHAValidator) GetValidationAssetName

func (v *SHAValidator) GetValidationAssetName(releaseFilename string) string

GetValidationAssetName returns the asset name for SHA256 validation.

func (*SHAValidator) Validate

func (v *SHAValidator) Validate(_ string, release, asset []byte) error

Validate checks the SHA256 sum of the release against the contents of an additional asset file.

type Source

type Source interface {
	ListReleases(ctx context.Context, repository Repository) ([]SourceRelease, error)
	DownloadReleaseAsset(ctx context.Context, rel *Release, assetID int64) (io.ReadCloser, error)
}

Source interface to load the releases from (GitHubSource for example)

type SourceAsset

type SourceAsset interface {
	GetID() int64
	GetName() string
	GetSize() int
	GetBrowserDownloadURL() string
}

type SourceRelease

type SourceRelease interface {
	GetID() int64
	GetTagName() string
	GetDraft() bool
	GetPrerelease() bool
	GetPublishedAt() time.Time
	GetReleaseNotes() string
	GetName() string
	GetURL() string

	GetAssets() []SourceAsset
}

type Updater

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

Updater is responsible for managing the context of self-update.

func NewUpdater

func NewUpdater(config Config) (*Updater, error)

NewUpdater creates a new updater instance. If you don't specify a source in the config object, GitHub will be used

func (*Updater) DetectLatest

func (up *Updater) DetectLatest(
	ctx context.Context,
	repository Repository,
) (*Release, bool, error)

DetectLatest tries to get the latest version from the source provider. It fetches releases information from the source provider and find out the latest release with matching the tag names and asset names. Drafts and pre-releases are ignored. Assets would be suffixed by the OS name and the arch name such as 'foo_linux_amd64' where 'foo' is a command name. '-' can also be used as a separator. File can be compressed with zip, gzip, xz, bzip2, tar&gzip or tar&xz. So the asset can have a file extension for the corresponding compression format such as '.zip'. On Windows, '.exe' also can be contained such as 'foo_windows_amd64.exe.zip'.

func (*Updater) DetectVersion

func (up *Updater) DetectVersion(
	ctx context.Context,
	repository Repository,
	version string,
) (*Release, bool, error)

DetectVersion tries to get the given version from the source provider. And version indicates the required version.

func (*Updater) UpdateTo

func (up *Updater) UpdateTo(ctx context.Context, rel *Release, cmdPath string) error

UpdateTo downloads an executable from the source provider and replace current binary with the downloaded one. It downloads a release asset via the source provider so this function is available for update releases on private repository.

type Validator

type Validator interface {
	// Validate validates release bytes against an additional asset bytes.
	// See SHAValidator for more information.
	Validate(filename string, release, asset []byte) error
	// GetValidationAssetName returns the additional asset name containing the validation checksum.
	// The asset containing the checksum can be based on the release asset name
	// Please note if the validation file cannot be found, the DetectLatest and DetectVersion methods
	// will fail with a wrapped ErrValidationAssetNotFound error
	GetValidationAssetName(releaseFilename string) string
}

Validator represents an interface which enables additional validation of releases.

type Verifier

type Verifier interface {
	VerifySignature(checksum, signature []byte, h crypto.Hash, publicKey crypto.PublicKey) error
}

Verifier defines an interface for verifying an update's signature with a public key.

func NewECDSAVerifier

func NewECDSAVerifier() Verifier

NewECDSAVerifier returns a Verifier that uses the ECDSA algorithm to verify updates.

func NewRSAVerifier

func NewRSAVerifier() Verifier

NewRSAVerifier returns a Verifier that uses the RSA algorithm to verify updates.

Jump to

Keyboard shortcuts

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