upgrade

package
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Aug 13, 2026 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// EnvDisableUpdateCheck disables background version checks when set to 1/true/yes.
	EnvDisableUpdateCheck = "VOLCENGINE_CLI_DISABLE_UPDATE_CHECK"
	// EnvUpdateCheckTTLHours overrides the default 24h cache TTL.
	EnvUpdateCheckTTLHours = "VOLCENGINE_CLI_UPDATE_CHECK_TTL_HOURS"
)
View Source
const (
	// EnvInstallMethod 覆盖安装来源识别(测试或排障用)。
	// 取值:standalone、npm、homebrew(大小写不敏感);linuxbrew 视为 homebrew。
	EnvInstallMethod = "VOLCENGINE_CLI_INSTALL_METHOD"

	// HomebrewFormula Homebrew 公式名,委托 brew 升级时使用。
	HomebrewFormula = "volcengine-cli"

	// NPMPackage npm 包名;用于升级委托(npm install -g)与后台升级提示命令。
	NPMPackage = "@volcengine/cli"
)
View Source
const (
	InternalUpgradeHelperCommand  = "__upgrade-helper"
	InternalUpgradeCleanupCommand = "__upgrade-cleanup"
	InternalUpgradeEnvironment    = "VOLCENGINE_CLI_INTERNAL_UPGRADE"
)
View Source
const CheckHTTPTimeout = 1500 * time.Millisecond

CheckHTTPTimeout is used for lightweight version detection.

View Source
const DefaultHTTPTimeout = 120 * time.Second

DefaultHTTPTimeout is used for upgrade downloads (longer than version checks).

View Source
const EnvDownloadBaseURL = "VOLCENGINE_CLI_DOWNLOAD_BASE_URL"

EnvDownloadBaseURL overrides the CDN base URL (same as npm install.js).

Variables

View Source
var ConfigDirFunc = defaultConfigDir

ConfigDirFunc returns the CLI config directory (default ~/.volcengine/). Overridable in tests. Prefer util.GetConfigFileDir from callers when wiring.

Functions

func ArchiveName

func ArchiveName(version, goos, goarch string) string

ArchiveName builds the release zip name for version/os/arch. Matches goreleaser / npm: volcengine-cli_{version}_{os}_{arch}.zip

func BinaryName

func BinaryName() string

BinaryName returns the CLI binary name for the current OS.

func CDNBaseURL

func CDNBaseURL() string

CDNBaseURL returns the configured CDN base.

func CheckCachePath

func CheckCachePath() (string, error)

CheckCachePath returns ~/.volcengine/cli/version_check.json

func ChecksumForArchive

func ChecksumForArchive(content, archiveName string) (string, error)

ChecksumForArchive returns the expected SHA256 hex for archiveName.

func ChecksumName

func ChecksumName(version string) string

ChecksumName builds the SHA256SUMS asset name for a version.

func DoUpgrade

func DoUpgrade(opts Options) error

DoUpgrade 按安装来源升级 CLI:

  • Homebrew:委托 brew update / brew upgrade
  • npm:委托 npm install -g;失败则返回错误并附带手动安装命令
  • standalone:从 CDN/GitHub 下载并原地替换当前二进制

func DownloadFile

func DownloadFile(w io.Writer, url, destPath string) error

DownloadFile downloads url into destPath. Progress is written to w when non-nil. Content is written to a same-directory temp file first, then renamed to destPath so a failed/partial download never leaves a truncated final path. When Content-Length is present, the transferred size must match.

func ExtractBinaryFromZip

func ExtractBinaryFromZip(archivePath, destPath, binaryName string) error

ExtractBinaryFromZip finds binaryName in the zip and writes it to destPath with 0755. Writes via a same-directory temp file then renames, so a failed extract never leaves a truncated destPath.

func FetchURLBytes

func FetchURLBytes(client *http.Client, url string, limit int64) ([]byte, error)

FetchURLBytes GETs url and returns the body (limited for small payloads). If the response is larger than limit, returns an error instead of a truncated body.

func FileSHA256

func FileSHA256(path string) (string, error)

FileSHA256 returns the hex-encoded SHA256 of a file.

func FormatUpgradeNotice

func FormatUpgradeNotice(current, latest string) string

FormatUpgradeNotice 生成单行 stderr 升级提示(无尾部换行)。 建议命令会随当前二进制的安装来源变化(npm / brew / ve upgrade)。

func FormatUpgradeNoticeFor

func FormatUpgradeNoticeFor(current, latest string, info InstallInfo) string

FormatUpgradeNoticeFor 与 FormatUpgradeNotice 相同,但安装来源由调用方显式传入(便于测试)。

func HomebrewUpgradeCommand

func HomebrewUpgradeCommand() string

HomebrewUpgradeCommand 生成推荐的 brew 升级命令。

func InvalidateCheckCache

func InvalidateCheckCache()

InvalidateCheckCache removes the version check cache (best-effort). Does not delete the sibling .lock file: unlinking a held lock path allows a second process to create a new inode and take a concurrent "exclusive" lock.

func IsNewer

func IsNewer(current, latest string) bool

IsNewer reports whether latest is strictly newer than current. Uses a simplified semver compare (major.minor.patch[-prerelease]).

When versions are not both valid semver:

  • latest is valid, current is not → true (can upgrade from opaque/dev builds)
  • otherwise → false (cannot prove "newer"; avoids false upgrade notices)

func IsZipPath

func IsZipPath(path string) bool

IsZipPath reports whether path looks like a zip archive.

func LaunchWindowsUpgradeHelper

func LaunchWindowsUpgradeHelper(opts WindowsUpgradeLaunchOptions) error

LaunchWindowsUpgradeHelper copies the running CLI to a temporary executable and starts it without waiting. The copy remains runnable after the parent releases the target executable's Windows image lock.

func LoadCheckCache

func LoadCheckCache() (versionCheckCache, bool)

LoadCheckCache reads the local version check cache. ok=true only for a fresh success entry or an in-window soft-failure backoff. Stale entries return ok=false; callers that need last-known Latest on remote failure should use lastKnownLatest().

func MaybePrintUpgradeNotice

func MaybePrintUpgradeNotice(stderr *os.File, currentVersion string, ac *AsyncCheck)

MaybePrintUpgradeNotice prints to stderr when an update is available. Throttle: the same running current version is reminded at most once per local calendar day; after current changes (upgrade), another notice is allowed even the same day. Claims the slot under a cross-process file lock before printing so concurrent ve processes print at most once when locking succeeds. Never writes to stdout.

func NPMUpgradeCommand

func NPMUpgradeCommand(pinVersion string) string

NPMUpgradeCommand 生成推荐的 npm 升级命令;pinVersion 非空则固定该版本。

func NormalizeVersion

func NormalizeVersion(version string) string

NormalizeVersion strips a leading "v"/"V" and surrounding space.

func OfficialReleasesURL

func OfficialReleasesURL() string

OfficialReleasesURL is used in user-facing error messages.

func ParseChecksumEntries

func ParseChecksumEntries(content string) (map[string]string, error)

ParseChecksumEntries parses a SHA256SUMS file (goreleaser / npm format). Each non-empty line: "<64-hex> filename" or "<64-hex> *filename".

func ReplaceBinary

func ReplaceBinary(newPath, currentPath string) error

ReplaceBinary atomically replaces currentPath with the file at newPath. On failure, the original binary is restored when possible.

func ReplaceBinaryWithBackup

func ReplaceBinaryWithBackup(newPath, currentPath, expectedVersion string) error

ReplaceBinaryWithBackup replaces current with newPath under an inter-process lock, keeping a unique same-directory backup until self-check succeeds. On self-check failure, restores the backup.

func ResolveExecPath

func ResolveExecPath() (string, error)

ResolveExecPath returns the real path of the current CLI binary.

func ResolveLatestVersion

func ResolveLatestVersion() (string, error)

ResolveLatestVersion finds the latest release version (upgrade path, full timeout). Order: CDN version_manifest.json → CDN latest text → GitHub Releases API.

func ResolveLatestVersionQuick

func ResolveLatestVersionQuick() (string, error)

ResolveLatestVersionQuick is for background checks: short timeout only, no long fallback.

func RollbackBinary

func RollbackBinary(backupPath, currentPath string) error

RollbackBinary restores backupPath over currentPath. Prefer rename (atomic replace on Unix). If that fails (common on Windows when the target exists), copy over the target without deleting it first so a failed rollback never leaves currentPath missing while the backup still exists.

func RunWindowsUpgradeCleanup

func RunWindowsUpgradeCleanup(parentPID int, workDir string) error

RunWindowsUpgradeCleanup waits for the helper executable to exit, then retries deletion because virus scanners can briefly retain Windows handles.

func RunWindowsUpgradeHelper

func RunWindowsUpgradeHelper(opts WindowsUpgradeHelperOptions) error

RunWindowsUpgradeHelper waits for the parent to release the running binary, replaces it, performs the self-check/rollback, and reports the real outcome.

func SameVersion

func SameVersion(a, b string) bool

SameVersion reports whether two version strings refer to the same release.

func SaveCheckCache

func SaveCheckCache(latest, current string) error

SaveCheckCache persists a successful check result. Preserves notice throttle fields so a refresh check does not re-enable spam.

func SaveCheckFailure

func SaveCheckFailure(previousLatest, current string) error

SaveCheckFailure persists a short backoff marker after a failed remote check. Keeps the previous Latest when available so we can still surface a notice from the last known good value without hitting the network. Preserves notice throttle fields so throttling survives a soft failure.

func SelfCheckVersion

func SelfCheckVersion(path, expectedVersion string) error

SelfCheckVersion runs `path version` and verifies the printed version matches expected. The child process is killed if it does not finish within selfCheckTimeout.

func SetCheckHTTPClient

func SetCheckHTTPClient(c *http.Client)

SetCheckHTTPClient overrides the version-check client (tests).

func SetHTTPClient

func SetHTTPClient(c *http.Client)

SetHTTPClient overrides the download client (tests).

func ShouldSkipBackgroundCheck

func ShouldSkipBackgroundCheck(args []string) bool

ShouldSkipBackgroundCheck returns true when the current invocation should not run a background version check (e.g. ve upgrade itself).

Only the first root positional argument is considered: if it is "upgrade", skip. Flag values (and future root value-flags) are not mistaken for the subcommand, and parameter values like --profile upgrade are not either.

func UpdateCheckDisabled

func UpdateCheckDisabled() bool

UpdateCheckDisabled reports whether background checks are disabled via env.

func ValidateVersion

func ValidateVersion(version string) error

ValidateVersion rejects empty or path-like version strings used in download URLs. Accepts common release forms: 1.0.49, v1.0.49, 1.0.49-rc.1.

func VerifyFileChecksum

func VerifyFileChecksum(path, expectedHex string) error

VerifyFileChecksum checks path against expected hex SHA256.

Types

type AssetSource

type AssetSource struct {
	Version      string
	ArchiveName  string
	ArchiveURL   string
	ChecksumURL  string
	ChecksumName string
}

AssetSource describes where to download a given version's archive and checksums.

func ResolveAssetSource

func ResolveAssetSource(version string) (*AssetSource, error)

ResolveAssetSource builds download URLs for a target version. Prefers CDN layout; archive/checksum paths match npm install.js. When the CDN probe fails, falls back to GitHub Releases. If both fail, returns an error that includes CDN probe status and the GitHub failure (instead of pretending resolve succeeded and deferring a vague download error).

type AsyncCheck

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

AsyncCheck is a background version check started at process entry.

func StartBackgroundCheck

func StartBackgroundCheck(currentVersion string, args []string) *AsyncCheck

StartBackgroundCheck launches a non-blocking version check when needed. Returns nil if checks are skipped or cache is already fresh with no need to re-fetch (still returns an AsyncCheck when cache has an update to report).

func (*AsyncCheck) TryResult

func (a *AsyncCheck) TryResult() (CheckResult, bool)

TryResult returns a completed check without waiting for network I/O.

func (*AsyncCheck) Wait

func (a *AsyncCheck) Wait(timeout time.Duration) CheckResult

Wait returns the check result, waiting up to timeout for in-flight network checks.

type CheckResult

type CheckResult struct {
	Current   string
	Latest    string
	HasUpdate bool
	CheckedAt time.Time
	FromCache bool
	Err       error
}

CheckResult is the outcome of a version check.

func CheckForUpdate

func CheckForUpdate(currentVersion string) CheckResult

CheckForUpdate resolves latest version (using cache when fresh).

type DetectContext

type DetectContext struct {
	ExecPath  string
	LookupEnv func(string) string
}

DetectContext 识别过程中的上下文(环境变量等)。

type DetectedBy

type DetectedBy string

DetectedBy 记录最终采用了哪一类识别信号。

const (
	DetectedByEnv     DetectedBy = "env"     // 环境变量覆盖
	DetectedByPath    DetectedBy = "path"    // 可执行路径启发式
	DetectedByDefault DetectedBy = "default" // 默认 standalone
)

type Detector

type Detector interface {
	Method() Method
	Match(normalizedPath string) bool // normalizedPath 已规范化(斜杠 + 小写)
	Info(execPath string) InstallInfo
}

Detector 单一安装来源的匹配器;defaultDetectors 中按顺序匹配,先命中先生效。

type InstallInfo

type InstallInfo struct {
	Method      Method     // 安装来源
	ExecPath    string     // 参与识别的可执行路径
	DetectedBy  DetectedBy // 命中的识别信号
	DisplayName string     // 展示用名称(如 npm、Homebrew)
	UpgradeCmd  string     // 建议的升级命令(一行)
}

InstallInfo 安装来源识别结果,供升级策略与后台提示使用。

func DetectInstall

func DetectInstall(execPath string) InstallInfo

DetectInstall 根据可执行文件路径判断安装来源。 无法识别时返回 standalone,不返回 error。

func DetectInstallFromRunningBinary

func DetectInstallFromRunningBinary() InstallInfo

DetectInstallFromRunningBinary 识别当前正在运行的 ve 的安装来源。 解析失败时回退为 standalone,供后台升级提示尽力而为。

func (InstallInfo) Managed

func (i InstallInfo) Managed() bool

Managed 表示是否由包管理器托管(非 standalone 即视为托管)。

type Method

type Method string

Method 表示当前 ve 二进制的安装来源。

const (
	// MethodStandalone 独立安装:Release 解压、源码编译等,允许原地替换。
	MethodStandalone Method = "standalone"
	// MethodNPM 通过 npm 全局包安装。
	MethodNPM Method = "npm"
	// MethodHomebrew 通过 Homebrew / Linuxbrew 安装(macOS 与 Linux)。
	MethodHomebrew Method = "homebrew"
)

type Options

type Options struct {
	// CurrentVersion 当前运行的 CLI 版本(必填)。
	CurrentVersion string
	// TargetVersion 目标版本;空表示升级到 latest。
	TargetVersion string
	// Yes 跳过交互确认。
	Yes bool
	// Stdout / Stderr 面向用户的输出,默认 os.Stdout/Stderr。
	Stdout io.Writer
	Stderr io.Writer
	// Stdin 确认交互输入,默认 os.Stdin。
	Stdin io.Reader
	// SkipSelfCheck 跳过安装后版本自检(测试用)。
	SkipSelfCheck bool
	// ExecPath 覆盖安装目标路径(测试用);空则使用当前可执行文件。
	ExecPath string
}

Options 控制 DoUpgrade 行为。

type VersionManifest

type VersionManifest struct {
	Latest         string `json:"latest"`
	MinSupported   string `json:"min_supported"`
	SecurityUpdate bool   `json:"security_update"`
	Channels       struct {
		CDNBase string `json:"cdn_base"`
	} `json:"channels"`
}

VersionManifest is the official CDN version listing.

type WindowsUpgradeHelperOptions

type WindowsUpgradeHelperOptions struct {
	ParentPID       int
	NewBinaryPath   string
	TargetPath      string
	WorkDir         string
	CurrentVersion  string
	ExpectedVersion string
	ExplicitTarget  bool
	SkipSelfCheck   bool
	Stdout          io.Writer
	Stderr          io.Writer
}

WindowsUpgradeHelperOptions describes the work performed after the parent exits.

type WindowsUpgradeLaunchOptions

type WindowsUpgradeLaunchOptions struct {
	CurrentExecutable string
	NewBinaryPath     string
	TargetPath        string
	WorkDir           string
	CurrentVersion    string
	ExpectedVersion   string
	ExplicitTarget    bool
	SkipSelfCheck     bool
	Stdout            io.Writer
	Stderr            io.Writer
}

WindowsUpgradeLaunchOptions describes the parent-side helper launch.

Jump to

Keyboard shortcuts

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