Documentation
¶
Index ¶
- Constants
- Variables
- func ArchiveName(version, goos, goarch string) string
- func BinaryName() string
- func CDNBaseURL() string
- func CheckCachePath() (string, error)
- func ChecksumForArchive(content, archiveName string) (string, error)
- func ChecksumName(version string) string
- func DoUpgrade(opts Options) error
- func DownloadFile(w io.Writer, url, destPath string) error
- func ExtractBinaryFromZip(archivePath, destPath, binaryName string) error
- func FetchURLBytes(client *http.Client, url string, limit int64) ([]byte, error)
- func FileSHA256(path string) (string, error)
- func FormatUpgradeNotice(current, latest string) string
- func FormatUpgradeNoticeFor(current, latest string, info InstallInfo) string
- func HomebrewUpgradeCommand() string
- func InvalidateCheckCache()
- func IsNewer(current, latest string) bool
- func IsZipPath(path string) bool
- func LaunchWindowsUpgradeHelper(opts WindowsUpgradeLaunchOptions) error
- func LoadCheckCache() (versionCheckCache, bool)
- func MaybePrintUpgradeNotice(stderr *os.File, currentVersion string, ac *AsyncCheck)
- func NPMUpgradeCommand(pinVersion string) string
- func NormalizeVersion(version string) string
- func OfficialReleasesURL() string
- func ParseChecksumEntries(content string) (map[string]string, error)
- func ReplaceBinary(newPath, currentPath string) error
- func ReplaceBinaryWithBackup(newPath, currentPath, expectedVersion string) error
- func ResolveExecPath() (string, error)
- func ResolveLatestVersion() (string, error)
- func ResolveLatestVersionQuick() (string, error)
- func RollbackBinary(backupPath, currentPath string) error
- func RunWindowsUpgradeCleanup(parentPID int, workDir string) error
- func RunWindowsUpgradeHelper(opts WindowsUpgradeHelperOptions) error
- func SameVersion(a, b string) bool
- func SaveCheckCache(latest, current string) error
- func SaveCheckFailure(previousLatest, current string) error
- func SelfCheckVersion(path, expectedVersion string) error
- func SetCheckHTTPClient(c *http.Client)
- func SetHTTPClient(c *http.Client)
- func ShouldSkipBackgroundCheck(args []string) bool
- func UpdateCheckDisabled() bool
- func UpdateCheckFailureBackoff() time.Duration
- func UpdateCheckTTL() time.Duration
- func ValidateVersion(version string) error
- func VerifyFileChecksum(path, expectedHex string) error
- type AssetSource
- type AsyncCheck
- type CheckResult
- type DetectContext
- type DetectedBy
- type Detector
- type InstallInfo
- type Method
- type Options
- type VersionManifest
- type WindowsUpgradeHelperOptions
- type WindowsUpgradeLaunchOptions
Constants ¶
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" )
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" )
const ( InternalUpgradeHelperCommand = "__upgrade-helper" InternalUpgradeCleanupCommand = "__upgrade-cleanup" InternalUpgradeEnvironment = "VOLCENGINE_CLI_INTERNAL_UPGRADE" )
const CheckHTTPTimeout = 1500 * time.Millisecond
CheckHTTPTimeout is used for lightweight version detection.
const DefaultHTTPTimeout = 120 * time.Second
DefaultHTTPTimeout is used for upgrade downloads (longer than version checks).
const EnvDownloadBaseURL = "VOLCENGINE_CLI_DOWNLOAD_BASE_URL"
EnvDownloadBaseURL overrides the CDN base URL (same as npm install.js).
Variables ¶
var ConfigDirFunc = defaultConfigDir
ConfigDirFunc returns the CLI config directory (default ~/.volcengine/). Overridable in tests. Prefer util.GetConfigFileDir from callers when wiring.
Functions ¶
func ArchiveName ¶
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 CheckCachePath ¶
CheckCachePath returns ~/.volcengine/cli/version_check.json
func ChecksumForArchive ¶
ChecksumForArchive returns the expected SHA256 hex for archiveName.
func ChecksumName ¶
ChecksumName builds the SHA256SUMS asset name for a version.
func DoUpgrade ¶
DoUpgrade 按安装来源升级 CLI:
- Homebrew:委托 brew update / brew upgrade
- npm:委托 npm install -g;失败则返回错误并附带手动安装命令
- standalone:从 CDN/GitHub 下载并原地替换当前二进制
func DownloadFile ¶
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 ¶
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 ¶
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 ¶
FileSHA256 returns the hex-encoded SHA256 of a file.
func FormatUpgradeNotice ¶
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 ¶
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 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 ¶
NPMUpgradeCommand 生成推荐的 npm 升级命令;pinVersion 非空则固定该版本。
func NormalizeVersion ¶
NormalizeVersion strips a leading "v"/"V" and surrounding space.
func OfficialReleasesURL ¶
func OfficialReleasesURL() string
OfficialReleasesURL is used in user-facing error messages.
func ParseChecksumEntries ¶
ParseChecksumEntries parses a SHA256SUMS file (goreleaser / npm format). Each non-empty line: "<64-hex> filename" or "<64-hex> *filename".
func ReplaceBinary ¶
ReplaceBinary atomically replaces currentPath with the file at newPath. On failure, the original binary is restored when possible.
func ReplaceBinaryWithBackup ¶
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 ¶
ResolveExecPath returns the real path of the current CLI binary.
func ResolveLatestVersion ¶
ResolveLatestVersion finds the latest release version (upgrade path, full timeout). Order: CDN version_manifest.json → CDN latest text → GitHub Releases API.
func ResolveLatestVersionQuick ¶
ResolveLatestVersionQuick is for background checks: short timeout only, no long fallback.
func RollbackBinary ¶
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 ¶
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 ¶
SameVersion reports whether two version strings refer to the same release.
func SaveCheckCache ¶
SaveCheckCache persists a successful check result. Preserves notice throttle fields so a refresh check does not re-enable spam.
func SaveCheckFailure ¶
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 ¶
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 ¶
SetCheckHTTPClient overrides the version-check client (tests).
func SetHTTPClient ¶
SetHTTPClient overrides the download client (tests).
func ShouldSkipBackgroundCheck ¶
ShouldSkipBackgroundCheck returns true when the current invocation should not run a background version check (e.g. ve upgrade itself or a delegated CLI).
Only the first root positional argument is considered. 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 UpdateCheckFailureBackoff ¶ added in v1.1.9
UpdateCheckFailureBackoff exposes ve's soft-failure retry interval.
func UpdateCheckTTL ¶ added in v1.1.9
UpdateCheckTTL exposes the configured background-check TTL to companion managers that intentionally share ve's update policy.
func ValidateVersion ¶
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 ¶
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 ¶
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 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.