selfupdate

package
v0.11.1 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 33 Imported by: 0

Documentation

Overview

Package selfupdate upgrades the running gskill executable from a signed GitHub release, or reports how its package manager upgrades it.

Only a standalone install (a release archive or the install script) is ever replaced. Homebrew, npm, Go, container, and other managed installs are detected from the executable's path and build info and get the command their own tool upgrades with; their files are never written.

Trust model: a release is installed only after its checksums.txt verifies as signed, keyless, by .github/workflows/release.yml of glapsfun/gskill at the target tag, the same identity the npm release pipeline checks. The archive must then match that manifest, and the extracted binary must run on this platform and report the target version. Renaming that workflow file breaks upgrades for every deployed gskill, so its path is part of the contract (spec 031).

Index

Constants

View Source
const DefaultAPIBase = "https://api.github.com/repos/glapsfun/gskill"

DefaultAPIBase is the GitHub API base for the gskill repository.

Variables

This section is empty.

Functions

func ArchiveName

func ArchiveName(version, goos, goarch string) string

ArchiveName is the release archive name for a platform. It is the archive naming contract in .goreleaser.yaml, which scripts/install.sh also relies on.

func CheckPlatform

func CheckPlatform(path, goos, goarch string) error

CheckPlatform fails unless the file at path is an executable for goos and goarch. It reads only the header, so a foreign binary is reported clearly instead of failing to start.

func CheckWritable

func CheckWritable(exe string) error

CheckWritable proves the executable's directory can take the replacement by creating and removing a staged file there. It is the authoritative check, run under the lock right before anything is downloaded.

func ChecksumFor

func ChecksumFor(manifest []byte, name string) (string, error)

ChecksumFor returns the SHA-256 that the manifest lists for name. The manifest must hold exactly one line for it.

func Cleanup

func Cleanup(dir string) error

Cleanup removes staged and backup files an interrupted upgrade left in dir. Callers hold the directory lock, so no other upgrade is using them.

func Discard

func Discard(backup string) error

Discard removes a backup once the new executable has checked out.

func ExtractBinary

func ExtractBinary(r io.Reader, name, wantSHA256 string, dst io.Writer, maxBinary int64) error

ExtractBinary streams the archive r, writes its gskill binary to dst, and checks that the whole archive matches wantSHA256. The digest is only known once the stream ends, so callers must not install dst unless it returns nil.

func Install

func Install(exe, staged string) (backup string, err error)

Install puts staged at exe and returns a backup of the old executable. It renames rather than copies: rename is the only atomic replacement, so exe is always one complete file, and on macOS arm64 writing into a signed binary in place gets its next run killed.

func NextCommand

func NextCommand(inst Installation, pin string) []string

NextCommand returns the lines that tell the user how the owner of inst upgrades it. pin is the version requested with --to, or "" for the latest.

func ProbeVersion

func ProbeVersion(ctx context.Context, path string, timeout time.Duration) (string, error)

ProbeVersion runs `<path> version --json` with stdin closed and returns the version it reports. Callers run it on the staged binary only after its archive digest is authenticated, on the running executable, and on the gskill PATH finds first, which the user would run anyway.

func ResolveExecutable

func ResolveExecutable(exe func() (string, error), args0 string, lookPath func(string) (string, error)) (executable, invokedAs string, err error)

ResolveExecutable returns the running executable with symlinks resolved, and the path it was invoked through when that is a different (symlinked) path.

func Restore

func Restore(exe, backup string) error

Restore moves the backup back over exe.

func Stage

func Stage(dir string, like os.FileInfo) (*os.File, error)

Stage creates the file the new binary is written to, in dir and with like's permission bits, so the final rename stays on one filesystem.

Types

type Action

type Action string

Action is what a plan will do.

const (
	ActionUpgrade     Action = "upgrade"
	ActionNone        Action = "none"
	ActionPrintAction Action = "print-action"
)

The plan actions.

type Asset

type Asset struct {
	Name string
	URL  string
	Size int64
}

Asset is one downloadable file of a release.

type BuildInfo

type BuildInfo struct {
	Version    string
	Kind       version.BuildKind
	ModulePath string
}

BuildInfo describes how the running binary was built.

type Channel

type Channel string

Channel is how the running gskill was installed.

const (
	ChannelStandalone  Channel = "standalone"
	ChannelHomebrew    Channel = "homebrew"
	ChannelNPMGlobal   Channel = "npm-global"
	ChannelNPMProject  Channel = "npm-project"
	ChannelNPX         Channel = "npx"
	ChannelNPM         Channel = "npm"
	ChannelGo          Channel = "go"
	ChannelContainer   Channel = "container"
	ChannelDevelopment Channel = "development"
	ChannelUnknown     Channel = "unknown"
)

The installation channels; contracts in spec 031 define the evidence for each.

type DetectInput

type DetectInput struct {
	Executable string
	InvokedAs  string
	Build      BuildInfo
	Getenv     func(string) string
	ReadFile   func(string) ([]byte, error)
}

DetectInput is what channel detection reads. Detection never runs a package manager and never touches the network.

type Env

type Env struct {
	Source     Source
	Verifier   Verifier
	Executable func() (string, error)
	// Args0 is the name the process was started with, used to report the
	// symlink an executable was invoked through.
	Args0    string
	LookPath func(string) (string, error)
	Getenv   func(string) string
	ReadFile func(string) ([]byte, error)
	Build    BuildInfo
	// Probe runs `<path> version --json` and returns the reported version.
	Probe       func(ctx context.Context, path string) (string, error)
	LockTimeout time.Duration
	GOOS        string
	GOARCH      string
}

Env is everything an upgrade reads from the outside world. Production code builds it from the real process; tests replace parts of it.

type GitHubSource

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

GitHubSource reads gskill releases from the GitHub REST API.

func NewGitHubSource

func NewGitHubSource(client *http.Client, apiBase, token string) *GitHubSource

NewGitHubSource returns a source for the repository at apiBase. A nil client builds the production clients: metadata requests time out after 15 seconds, while asset downloads only bound the wait for response headers, so a slow link can still finish a large archive. token, when set, is sent to the API only, never to the asset host.

func (*GitHubSource) ByTag

func (s *GitHubSource) ByTag(ctx context.Context, tag string) (Release, error)

ByTag returns the release published under tag.

func (*GitHubSource) Latest

func (s *GitHubSource) Latest(ctx context.Context) (Release, error)

Latest returns the newest stable release. GitHub's "latest" never returns a draft or a prerelease.

func (*GitHubSource) Open

func (s *GitHubSource) Open(ctx context.Context, a Asset) (io.ReadCloser, error)

Open starts downloading a. The body fails once it passes a.Size, and a.Size itself must be within the cap for that kind of asset.

type Installation

type Installation struct {
	Executable string
	InvokedAs  string
	Version    string
	Kind       version.BuildKind
	OS         string
	Arch       string
	Channel    Channel
	Evidence   string
	PathShadow *ShadowExecutable
	// NPMProjectDir is the project whose package.json declares gskill, set
	// only for ChannelNPMProject.
	NPMProjectDir string
	// GoInstallDir is where `go install` writes binaries (GOBIN, else
	// GOPATH/bin, else ~/go/bin), set only for ChannelGo.
	GoInstallDir string
}

Installation is the gskill that is running.

func Detect

func Detect(in DetectInput) Installation

Detect classifies the installation from positive evidence only. The rules run in order and the first match wins; anything unproven is unknown, and only ChannelStandalone is ever replaced.

func (Installation) Platform

func (i Installation) Platform() string

Platform returns the installation's "<os>/<arch>".

type Outcome

type Outcome struct {
	Kind             OutcomeKind
	Upgraded         bool
	PreviousVersion  string
	TargetVersion    string
	InstalledVersion string
	Executable       string
	Platform         string
	InvokedAs        string
	Channel          Channel
	Evidence         string
	NextCommand      []string
	PathShadow       *ShadowExecutable
	Err              error
}

Outcome is the single result of a run, for humans and for --json.

func Apply

func Apply(ctx context.Context, env Env, p UpgradePlan, progress func(string)) (Outcome, error)

Apply carries out an ActionUpgrade plan. Every step must pass before the next starts, and until the final rename the executable is untouched.

func OutcomeFor

func OutcomeFor(p UpgradePlan) Outcome

OutcomeFor returns the outcome a plan reports without applying it: up to date, action required, or, for an upgrade, a dry run.

type OutcomeKind

type OutcomeKind string

OutcomeKind is the result of a run.

const (
	OutcomeUpgraded       OutcomeKind = "upgraded"
	OutcomeUpToDate       OutcomeKind = "up_to_date"
	OutcomeDryRun         OutcomeKind = "dry_run"
	OutcomeActionRequired OutcomeKind = "action_required"
	OutcomeDeclined       OutcomeKind = "declined"
	OutcomeFailed         OutcomeKind = "failed"
)

The outcome kinds, spelled as the JSON "outcome" field.

type PlanRequest

type PlanRequest struct {
	// To is the exact version requested with --to, or empty for the latest
	// stable release.
	To string
}

PlanRequest carries the user's choices for a self-upgrade.

type Release

type Release struct {
	Version    *semver.Version
	Tag        string
	Prerelease bool
	Draft      bool
	Assets     []Asset
}

Release is one published gskill version.

func (Release) Asset

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

Asset returns the release asset with exactly this name.

type ShadowExecutable

type ShadowExecutable struct {
	Path    string
	Version string
}

ShadowExecutable is a different gskill found first on PATH.

func Shadow

func Shadow(ctx context.Context, env Env, executable string) *ShadowExecutable

Shadow returns the gskill that PATH finds first when it is a different executable from the one running, so the user knows `gskill version` there will not change. It is never modified.

type SigstoreVerifier

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

SigstoreVerifier checks release manifests against the Sigstore public-good instance, whose trusted root it refreshes through TUF.

func NewSigstoreVerifier

func NewSigstoreVerifier(cacheDir string, noCache bool) *SigstoreVerifier

NewSigstoreVerifier returns a verifier that caches TUF metadata under cacheDir/sigstore-tuf, or keeps it in memory when noCache is set or cacheDir is empty.

func (*SigstoreVerifier) VerifyManifest

func (v *SigstoreVerifier) VerifyManifest(_ context.Context, manifest, bundleJSON []byte, tag string) error

VerifyManifest authenticates manifest against its bundle for tag.

type Source

type Source interface {
	Latest(ctx context.Context) (Release, error)
	ByTag(ctx context.Context, tag string) (Release, error)
	Open(ctx context.Context, a Asset) (io.ReadCloser, error)
}

Source finds published releases and opens their assets.

type UpgradePlan

type UpgradePlan struct {
	Installation Installation
	Target       *Release
	Requested    string
	Action       Action
	NextCommand  []string
}

UpgradePlan is what the command will do, decided before any write.

func Plan

func Plan(ctx context.Context, env Env, req PlanRequest) (UpgradePlan, error)

Plan decides what a self-upgrade would do, without writing anything. A refusal comes back as an error. A package-managed install with a newer release returns its plan together with an "update available" error, so the caller can print the command and still exit 8.

type Verifier

type Verifier interface {
	VerifyManifest(ctx context.Context, manifest, bundle []byte, tag string) error
}

Verifier authenticates a release's checksum manifest against its signature bundle for the given tag.

Directories

Path Synopsis
Package selfupdatetest holds test helpers for the self-upgrade code: a fake GitHub release server, a fake signature verifier, an in-memory archive builder, and a small fake gskill binary built on demand.
Package selfupdatetest holds test helpers for the self-upgrade code: a fake GitHub release server, a fake signature verifier, an in-memory archive builder, and a small fake gskill binary built on demand.

Jump to

Keyboard shortcuts

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