update

package
v0.157.0 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 17 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 `gk update` — self-update with install-source detection. brew installs are forwarded to `brew upgrade`, manual installs (curl install.sh) self-replace via atomic rename, and `go install` builds surface a copy-pasteable upgrade command.

The package is deliberately runtime-only: no GitHub auth, no signature verification beyond the published `checksums.txt`, no auto-cron — all of those are upstream responsibilities or out of scope for a CLI updater.

Index

Constants

View Source
const DefaultRepo = "x-mesh/gk"

DefaultRepo is the upstream GitHub `owner/repo` target. Tests can swap in their own mux server by passing a custom Client.

Variables

View Source
var ErrSameFilesystem = errors.New("staged file and target must live on the same filesystem")

ErrSameFilesystem signals an attempt to atomically rename across filesystems, which the OS rejects. Surfaced separately so callers can distinguish from other I/O errors and explain what happened.

Functions

func AtomicReplace

func AtomicReplace(staged, target string) error

AtomicReplace swaps `target` with `staged` and stashes the previous binary at `target + ".bak"` for trivial rollback. Both paths must be on the same filesystem — DownloadVerified arranges this by writing the staged file next to the target.

On Linux/macOS, replacing a binary that is currently executing is safe: the kernel pins the old inode for the running process, while new exec calls find the new file via the path lookup. So the running `gk update` continues to operate from the old binary, and the very next `gk` call uses the upgraded one.

func AtomicReplaceWithSudo

func AtomicReplaceWithSudo(staged, target string) error

AtomicReplaceWithSudo wraps AtomicReplace with a privilege-escalation fallback for the common /usr/local/bin install. When the target directory is not writable by the current user, we shell out to:

sudo install -m 0755 <staged> <target>

stdin/stdout/stderr are passed through so the user can answer the sudo password prompt directly. If sudo is missing we surface a clear error telling the user to rerun with privileges; we never silently fail.

Backup behaviour is intentionally skipped under sudo — copying the prior binary as root introduces ownership questions (whose .bak is it?) that outweigh the rollback convenience for what is meant to be a rare path.

func CompareSemver

func CompareSemver(a, b string) int

CompareSemver returns -1 if a < b, 0 if equal, +1 if a > b. Both inputs may carry a leading "v". A non-numeric segment is treated as the largest possible value, which makes "dev" comparisons against any release tag always trigger an update — exactly what unreleased builds want.

Pre-release suffixes (e.g. "-rc1") are ignored: "v0.30.0-rc1" compares equal to "v0.30.0". gk does not currently ship pre-releases, so handling them precisely is YAGNI.

func FormatPlan

func FormatPlan(current, next string) string

FormatPlan renders a one-line "current → next" string for human output.

func LinkAlias

func LinkAlias(dir, binName, aliasName string) error

LinkAlias creates (or refreshes) a relative symlink `aliasName` → `binName` inside dir, so the upgraded binary is reachable under its secondary name (git-kit) too. Mirrors install.sh's link_alt: a relative link survives the bin dir being moved, and an existing alias is replaced rather than left pointing at a stale copy.

Escalates with sudo when dir is not user-writable (the /usr/local/bin case), matching AtomicReplaceWithSudo. Callers treat failures as non-fatal — the primary binary is already in place by the time this runs.

func PickStagingDir

func PickStagingDir(installDir string) string

PickStagingDir returns installDir when the current user can write to it (so the eventual atomic rename stays on the same filesystem), otherwise os.TempDir() so the download step does not gate on the install dir's permission bits.

When this returns os.TempDir(), AtomicReplaceWithSudo will detect the non-writable target and fall through to `sudo install`, which performs a cross-filesystem copy via install(1). So callers do not need to track which path they got back — they just hand the staged file to AtomicReplaceWithSudo and the right strategy is chosen automatically.

Types

type BrewKind

type BrewKind string

BrewKind distinguishes the two Homebrew install shapes — the tap was migrated from a formula to a cask at v0.55+ and `brew upgrade` needs the `--cask` flag for the new shape. Empty for non-brew installs.

const (
	BrewKindNone    BrewKind = ""
	BrewKindFormula BrewKind = "formula"
	BrewKindCask    BrewKind = "cask"
)

type Client

type Client struct {
	HTTP         HTTPDoer // http.DefaultClient when nil
	Repo         string   // "x-mesh/gk" when ""
	APIBase      string   // "https://api.github.com" when ""
	DownloadBase string   // "https://github.com" when ""
}

Client talks to GitHub's release API and download host.

Default zero-value Client uses http.DefaultClient and DefaultRepo and is fine for production. Tests inject a custom HTTPDoer + APIBase + DownloadBase to redirect traffic to httptest.Server without a network round-trip.

func (*Client) AssetURL

func (c *Client) AssetURL(tag, asset string) string

AssetURL returns the direct-download URL for a release asset. Mirrors the documented `releases/download/<tag>/<asset>` layout used by goreleaser, the install.sh script, and the Homebrew tap formula.

func (*Client) DownloadVerified

func (c *Client) DownloadVerified(ctx context.Context, tag, asset, dir string) (string, error)

DownloadVerified fetches the release archive for `tag` and `asset`, verifies its sha256 against the published checksums.txt, extracts the `gk` binary into `dir`, and returns the absolute path to the extracted file.

`dir` is intentionally caller-controlled. For self-update we point it at the parent dir of the running binary so the eventual atomic rename does not cross filesystem boundaries.

func (*Client) LatestTag

func (c *Client) LatestTag(ctx context.Context) (string, error)

LatestTag returns the most recent release's tag (e.g. "v0.29.1").

Tries github.com's /releases/latest 302 redirect first — the redirect Location resolves to /<owner>/<repo>/releases/tag/<tag> and is served by the regular github.com host, which is not subject to api.github.com's 60/hour anonymous rate limit. This is the same trick install.sh uses.

Falls back to the api.github.com /releases/latest JSON endpoint when the redirect path fails (e.g. unexpected Location format), so we keep behaviour for environments that proxy github.com but not api.github.com.

type HTTPDoer

type HTTPDoer interface {
	Do(*http.Request) (*http.Response, error)
}

HTTPDoer is the subset of http.Client we depend on. Lets tests substitute a recording transport without juggling the full http.Client zoo.

type Install

type Install struct {
	Source     Source
	BrewKind   BrewKind // formula/cask when Source == SourceBrew; empty otherwise
	BinaryPath string   // resolved absolute path of the running gk binary
	Dir        string   // filepath.Dir(BinaryPath) — where a sibling gk.new lands
	OS         string   // runtime.GOOS
	Arch       string   // runtime.GOARCH
}

Install is the resolved environment for the running gk binary.

func DetectInstall

func DetectInstall() (*Install, error)

DetectInstall identifies how the running binary was installed.

The classification is structural — it inspects the binary path returned by os.Executable, after symlink resolution — rather than asking `brew list`. Asking brew would shell out and depend on PATH, which is exactly what we want to avoid in a self-updater.

func (*Install) AliasName

func (i *Install) AliasName() string

AliasName returns the secondary command name to expose alongside the running binary, mirroring install.sh's `git-kit` link and the cask's `binary "gk", target: "git-kit"`. The suffix is preserved so a dev build keeps its own namespace:

gk      → git-kit
gk-dev  → git-kit-dev

Returns "" when the binary name doesn't match the `gk[-suffix]` shape (e.g. a user renamed the binary), in which case callers skip alias creation rather than guess at an unrelated name.

func (*Install) AssetName

func (i *Install) AssetName() string

AssetName is the archive filename published in releases for this platform. Mirrors the `gk_<os>_<arch>.tar.gz` template in .goreleaser.yaml. Returns the empty string for unsupported platforms.

type Source

type Source int

Source classifies how the running gk binary was installed. The classifier is intentionally permissive: when in doubt it returns SourceManual, which triggers the safest path (download + atomic rename).

const (
	// SourceUnknown is the zero value. Indicates DetectInstall has not run.
	SourceUnknown Source = iota
	// SourceBrew means the binary lives under a Homebrew prefix and should
	// be upgraded via `brew upgrade x-mesh/tap/gk`.
	SourceBrew
	// SourceGoInstall means the binary lives under $GOPATH/bin or
	// $HOME/go/bin. We refuse to overwrite these and instead suggest
	// `go install ...@latest`.
	SourceGoInstall
	// SourceManual is everything else — typically /usr/local/bin/gk or
	// ~/.local/bin/gk from `install.sh`. Self-replace is allowed.
	SourceManual
)

func (Source) String

func (s Source) String() string

String returns a stable label for logs and human output.

Jump to

Keyboard shortcuts

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