update

package
v0.21.0 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2026 License: MIT Imports: 16 Imported by: 0 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.

Documentation

Overview

Package update implements pyrycode's self-update logic: release manifest parsing, version comparison, fetch, and replace. This file lands the pure-function half (parsing + comparison); the HTTP fetcher and the binary replacer arrive in sister tickets.

Index

Constants

This section is empty.

Variables

View Source
var ErrAssetNotInChecksums = errors.New("asset not listed in checksums")

ErrAssetNotInChecksums is returned by ParseChecksumsFile when the requested asset is not listed in the checksums.txt body.

View Source
var ErrBinaryNotInArchive = errors.New("binary not found in archive")

ErrBinaryNotInArchive is returned by ExtractBinary when the requested binaryName is not present as a regular file in the tar archive.

View Source
var ErrChecksumMismatch = errors.New("sha256 checksum mismatch")

ErrChecksumMismatch is returned by VerifySHA256 when the computed digest does not match the expected one.

View Source
var ErrInvalidPublicKey = errors.New("invalid signing public key")

ErrInvalidPublicKey is returned by VerifySignature when the supplied public key is not exactly ed25519.PublicKeySize (32) bytes. This guards against a malformed baked-in key constant so verification returns an error instead of ed25519.Verify panicking on a wrong-length key.

View Source
var ErrInvalidSignature = errors.New("checksums signature verification failed")

ErrInvalidSignature is returned by VerifySignature when the detached signature does not verify against the supplied data and public key — or when the signature is not exactly ed25519.SignatureSize (64) bytes. A caller only ever branches "signed correctly vs not", so one sentinel covers both the wrong-length and non-verifying cases.

View Source
var ErrInvalidVersion = errors.New("invalid semver version")

ErrInvalidVersion is returned by CompareVersions when either argument is not a parseable semver string.

View Source
var ErrMalformedArchive = errors.New("malformed tar.gz archive")

ErrMalformedArchive is returned by ExtractBinary when the input is not a valid gzip stream or the gzipped payload is not a valid tar archive.

View Source
var ErrMalformedChecksums = errors.New("malformed checksums file")

ErrMalformedChecksums is returned by ParseChecksumsFile when the input is empty or contains no parseable "<hex> <name>" lines at all.

View Source
var ErrMalformedRelease = errors.New("malformed release manifest")

ErrMalformedRelease is returned by ParseLatestRelease when the JSON is invalid, not an object, or missing/empty "tag_name".

View Source
var ErrUnsupportedPlatform = errors.New("unsupported os/arch")

ErrUnsupportedPlatform is returned by AssetName for any os/arch combo not built by .goreleaser.yaml.

Functions

func AssetName

func AssetName(version, goos, goarch string) (string, error)

AssetName returns the GoReleaser-produced tarball filename for the given version and host platform, e.g. AssetName("v0.9.1", "darwin", "arm64") → "pyry_0.9.1_Darwin_arm64.tar.gz".

A leading "v" on version is stripped (GoReleaser's name template uses the bare semver). The os/arch values follow Go's runtime.GOOS / runtime.GOARCH vocabulary: only the four combinations actually built by .goreleaser.yaml are supported (linux/darwin × amd64/arm64); any other combination returns an error wrapping ErrUnsupportedPlatform.

func AtomicReplace

func AtomicReplace(targetPath string, newData []byte, mode os.FileMode) error

AtomicReplace overwrites targetPath with newData using the standard POSIX write-temp + fsync + rename dance, so an interruption mid-write leaves targetPath pointing at either the old contents or the new contents — never a truncated file.

The new file is created with the supplied mode (applied via an explicit Chmod since os.CreateTemp opens at 0o600). targetPath does not need to exist beforehand; if it does, it is replaced in place.

SAME-FILESYSTEM CAVEAT: rename(2) is only atomic when source and destination are on the same filesystem. AtomicReplace creates its temp file in filepath.Dir(targetPath) precisely so the eventual rename never crosses a mount point. Callers MUST therefore pass a path whose parent directory already exists and is writable; AtomicReplace does not MkdirAll the parent.

On any error path before the successful rename, the temp file is removed so no stragglers accumulate in the install directory.

func DetectRestartCommand

func DetectRestartCommand(probe RestartProbe) []string

DetectRestartCommand returns the argv (program plus args) of the command that restarts a managed pyry daemon based on the supplied probe results, or nil when no managed daemon is detected and the caller should print "restart your pyry yourself" guidance.

Tie-breaker: when both LaunchdPlistExists and SystemdUnitExists are true, launchd wins. Rationale: macOS is pyrycode's primary daily-driver platform, so a stray systemd user unit on a Mac (e.g. left over from a dotfiles sync) is more likely cruft than the active manager. The reverse case — a launchd plist on Linux — cannot occur because launchctl does not exist on Linux; the probe will return false.

Pure function: no os.Stat, no runtime.GOOS, no exec. Caller probes and supplies inputs.

func ExtractBinary

func ExtractBinary(tgzData []byte, binaryName string) ([]byte, error)

ExtractBinary reads a gzipped tar archive entirely from memory and returns the bytes of the regular-file entry whose tar header Name matches binaryName (e.g. "pyry"). Memory-only: no temp files, no streaming-to-disk.

Matching is by exact tar header Name compared with filepath.Base — the GoReleaser archive lays files at the archive root (`pyry`, `LICENSE`, `docs/INSTALL.md`, ...) so callers pass the bare filename. Non-regular entries (directories, symlinks, hard links) are skipped; only the first matching regular file is returned.

Returns an error wrapping ErrMalformedArchive if tgzData is not a valid gzip stream or the decompressed payload is not a parseable tar archive. Returns an error wrapping ErrBinaryNotInArchive if no regular-file entry matches binaryName.

func ParseChecksumsFile

func ParseChecksumsFile(text, assetName string) (string, error)

ParseChecksumsFile finds the SHA-256 hex digest for assetName inside the contents of a GoReleaser-produced checksums.txt. Each non-empty line of the file is expected to be "<sha256-hex> <filename>" (two spaces between the digest and the filename, matching `sha256sum` output). Lines that don't match are skipped silently — GoReleaser may add trailing blank lines or future header comments.

On success returns the lowercase hex digest (64 characters). Returns an error wrapping ErrAssetNotInChecksums if no matching line is found, or ErrMalformedChecksums if the file is empty or contains no parseable lines at all.

func ParseLatestRelease

func ParseLatestRelease(jsonBytes []byte) (string, error)

ParseLatestRelease extracts the tag name from a GitHub Releases API JSON payload (e.g. the response body of GET /repos/{owner}/{repo}/releases/latest).

On success it returns the value of the top-level "tag_name" field (e.g. "v0.9.1" — the leading "v" is preserved verbatim; CompareVersions strips it).

Returns an error wrapping ErrMalformedRelease if jsonBytes is not valid JSON, if the document is not a JSON object, if "tag_name" is absent, or if "tag_name" is not a string. The empty string is also rejected as an absent tag.

func VerifySHA256

func VerifySHA256(data []byte, expectedHex string) error

VerifySHA256 returns nil iff sha256(data) lowercase-hex equals expectedHex. On mismatch the error includes both the expected and actual digests for diagnostic logging. expectedHex is matched case-insensitively (callers pass a value sourced from ParseChecksumsFile, which already lowercases, but this guards against future callers that don't).

func VerifySignature added in v0.16.0

func VerifySignature(data, sig []byte, pub ed25519.PublicKey) error

VerifySignature returns nil iff sig is a valid Ed25519 signature over data under pub. It is a pure function: no I/O, no logging, no context.

The signature is expected to be a raw 64-byte RFC 8032 Ed25519 signature over the exact bytes of data (for `pyry update`, the unmodified bytes of checksums.txt as served). There is no envelope, algorithm tag, or key id — a single algorithm and a single trust root means there is no algorithm-confusion or downgrade vector to defend against.

Length is checked before ed25519.Verify so a malformed key or signature yields a sentinel error rather than a panic. The returned error is a clean sentinel-carrier: it never includes the signature or key bytes.

Types

type Comparison

type Comparison int

Comparison is the result of comparing two semver versions. The values mirror cmp.Compare / strings.Compare conventions: negative when the first argument is less, zero when equal, positive when greater.

const (
	// Older means current is older than latest.
	Older Comparison = -1
	// Same means current and latest are equal.
	Same Comparison = 0
	// Newer means current is newer than latest.
	Newer Comparison = 1
)

func CompareVersions

func CompareVersions(current, latest string) (Comparison, error)

CompareVersions compares two semver version strings and reports whether current is older than, equal to, or newer than latest.

Both arguments may carry a leading "v" (e.g. "v0.9.1") or omit it ("0.9.1") — the prefix is stripped before parsing. Pre-release and build-metadata suffixes are stripped at the first '-' or '+' before numeric parsing (e.g. "v0.10.0-rc1" is compared as "0.10.0"). This is a deliberate simplification: pyry's tags are plain major.minor.patch and the comparator does not need to implement SemVer 2.0.0 precedence rules for pre-releases.

Returns an error wrapping ErrInvalidVersion if either argument cannot be parsed into three non-negative integers separated by dots after the prefix and suffix stripping above. The sentinel main.Version value "dev" is one such case — callers detecting a "dev" build should special-case it before invoking CompareVersions. On error the returned Comparison is Same; callers must check the error first.

type Fetcher

type Fetcher struct {
	// BaseURL is the API root for the latest-release endpoint.
	// Empty value defaults to "https://api.github.com".
	// Tests set this to httptest.NewServer's URL.
	BaseURL string

	// HTTPClient is the underlying transport. Empty value defaults to
	// http.DefaultClient. Callers wanting a request budget construct a
	// &http.Client{Timeout: 60*time.Second} and assign it here.
	HTTPClient *http.Client

	// UserAgent is sent on every request. Empty value defaults to
	// "pyry/dev". Callers in cmd/pyry set this to "pyry/" + main.Version
	// so GitHub's API doesn't blanket-reject anonymous traffic.
	UserAgent string
}

Fetcher performs the network reads required by the `pyry update` flow: the GitHub Releases API JSON and the release-asset bytes (tarball, checksums.txt). It is a thin wrapper over net/http: no retries, no caller-imposed timeouts, no body parsing — those concerns live elsewhere in this package and in the wiring ticket.

The zero value is usable and targets api.github.com with http.DefaultClient and a "pyry/dev" User-Agent. Callers in cmd/pyry override UserAgent to "pyry/" + main.Version and typically install an HTTPClient with an explicit Timeout (the fetcher does not impose one).

*Fetcher is safe for concurrent use: all fields are read after construction, *http.Client.Do is documented as concurrency-safe, and each call constructs a fresh *http.Request.

func (*Fetcher) FetchAsset

func (f *Fetcher) FetchAsset(ctx context.Context, url string) ([]byte, error)

FetchAsset GETs the given URL and returns the response body verbatim. The URL is typically extracted from the release JSON returned by FetchLatestRelease (assets[].browser_download_url for the tarball, or the URL of the checksums.txt asset). The User-Agent header is sent on this request, same as FetchLatestRelease.

Same error semantics as FetchLatestRelease.

func (*Fetcher) FetchLatestRelease

func (f *Fetcher) FetchLatestRelease(ctx context.Context, repo string) ([]byte, error)

FetchLatestRelease GETs <BaseURL>/repos/<repo>/releases/latest and returns the response body verbatim. repo is in "owner/name" form (e.g. "pyrycode/pyrycode"). The body is the raw GitHub Releases API JSON, suitable for passing to ParseLatestRelease.

Returns an error if the request cannot be constructed, the transport fails, the body cannot be read, or the response status is not 2xx. Non-2xx errors include the status code and the requested URL. Context cancellation propagates: an error wrapping context.Canceled or context.DeadlineExceeded is returned if ctx is done before the response body is fully received.

type RestartProbe

type RestartProbe struct {
	LaunchdPlistExists bool   // ~/Library/LaunchAgents/dev.pyrycode.pyry.plist
	SystemdUnitExists  bool   // ~/.config/systemd/user/pyry.service
	UID                string // numeric uid as string, templated into the launchctl gui/<uid>/... domain
}

RestartProbe carries the local-environment signals DetectRestartCommand needs to choose a restart command. The wiring ticket fills these from os.Stat on the platform-specific service file paths and from strconv.Itoa(os.Getuid()).

Jump to

Keyboard shortcuts

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