mirror of
https://github.com/larksuite/cli.git
synced 2026-07-07 17:45:15 +08:00
* refactor(cmd): split Execute into Build with IO/Keychain injection
Introduce a public cmd.Build entry point so external consumers (cli-server,
MCP server, other embedders) can assemble the full CLI command tree without
going through os.Args or the platform keychain. Build takes an
InvocationContext plus functional BuildOptions:
* WithIO(in, out, errOut) — inject custom streams; terminal detection
is derived from the input's underlying *os.File when present.
* WithKeychain(kc) — swap the credential store.
* HideProfile(bool) — registered later in cmd.HideProfile.
The existing Execute() keeps using the internal buildInternal (which
still returns the Factory so error handling can attribute exit codes),
and SetDefaultFS replaces the global VFS implementation at startup.
Hardening applied up front:
* cmdutil.NewIOStreams(in, out, errOut) centralizes terminal detection
so SystemIO() and WithIO share one path.
* cmdutil.NewDefault normalizes partial IOStreams — callers may pass
&IOStreams{Out: buf} without tripping nil-writer panics in the
RoundTripper warnings, Cobra, or the credential provider.
* Build guards against nil functional options.
* An API contract test (cmd/build_api_test.go) exercises Build +
WithIO + WithKeychain + HideProfile + SetDefaultFS so the public
surface is reachable by deadcode analysis.
Change-Id: I7c895e6019817401accbde2db3ef800da40ad319
* feat(schema): filter methods by strict mode in schema output
When strict mode is active, schema output now excludes methods that
are incompatible with the forced identity. This applies to both
pretty and JSON output formats at the resource and method levels.
Change-Id: I39647d5578466c3e23dc545bfb917ae075203ad7
* refactor: centralize strict-mode as flag registration
Change-Id: Iec11151c5002c2f58a8aa067d08747db2e4d2d8c
* fix(cmd): align strict-mode completion and build context; drop dead register shims
Thread a context.Context through RegisterShortcuts, RegisterServiceCommands,
and service.registerService/Resource/Method by introducing explicit
*WithContext variants. Pass that context into NewCmdServiceMethodWithContext
so shortcut and service command construction can honor cancellation and
strict-mode pruning consistently.
Also drop the context-less registerMethod and registerResource shims —
they became unreachable once the WithContext variants took over, and
were the source of new deadcode warnings. registerService is retained
because service_test.go still calls it directly.
Change-Id: I3fe5673aed663c7383bbbc5b0ae94d1f3491f22d
* refactor(cmd): hide --profile in single-app mode via build option
- GlobalOptions gains HideProfile; RegisterGlobalFlags stays pure and reads
the policy off the struct. No boolean-trap parameter, one call per site.
- buildConfig holds GlobalOptions inline so HideProfile(bool) BuildOption
mutates it directly. buildInternal stays a pure assembly function and
requires callers to supply WithIO — no implicit os.Std* fallback.
- Add WithIO BuildOption (wrapping raw io.Reader/Writer with automatic
*os.File TTY detection); Execute injects streams explicitly and decides
profile visibility via HideProfile(isSingleAppMode()).
- installTipsHelpFunc force-shows hidden root flags while rendering the
root command's own help, so single-app users still discover --profile
via lark-cli --help without it polluting subcommand helps.
Change-Id: I7755387e993992ca969e0a4a6f54441cc1993eef
* feat(transport): extension abort hook and shared base transport
Two transport-layer changes bundled because both reshape the base
round-tripper contract used by the HTTP client, the Lark SDK client,
and the in-process updater.
1. Extension abort hook (PreRoundTripE).
Extensions implementing exttransport.AbortableInterceptor can now
return an error from PreRoundTripE to skip the built-in chain. The
post hook still fires with (nil, reason) so extensions can unwind
resources. extensionMiddleware captures the provider name so the
returned *AbortError carries attribution.
2. Shared base transport to stop RPC leak.
util.NewBaseTransport cloned http.DefaultTransport on every call, so
each cmdutil.Factory produced a fresh *http.Transport whose
persistConn readLoop/writeLoop goroutines lingered until
IdleConnTimeout (~90s). Invisible in a single-process CLI, but the
fork is consumed by cli-server where each RPC request constructs a
new Factory, causing linear memory + goroutine growth under load.
Replace NewBaseTransport with SharedTransport — returns
http.DefaultTransport (the stdlib-wide singleton) by default, and
a cached proxy-disabled clone only when LARK_CLI_NO_PROXY is set.
Return type is http.RoundTripper to discourage in-place mutation of
the shared instance. FallbackTransport is kept as a thin
*http.Transport wrapper so existing callers in internal/auth and
internal/cmdutil transport decorators (which were already on the
singleton path) do not have to migrate.
Leak-site migrations: factory_default.go (HTTP + SDK base) and
update.go now call SharedTransport directly.
Change-Id: Ia82462134c5c5ee838be878b887860f41446a235
* fix: unblock Build() zero-opts path and sidecar demo build
Two regressions surfaced on refactor/build-execute-split:
1. cmd.Build(ctx, inv) without WithIO panicked at rootCmd.SetIn/Out/Err
because cfg.streams stayed nil — NewDefault normalized internally
but cmd/build.go never saw the normalized value. Default cfg.streams
to cmdutil.SystemIO() before the root command wires them, and add a
TestBuild_NoOptions regression guard.
2. sidecar/server-demo/main.go still called cmdutil.NewDefault(inv),
so `go build -tags authsidecar_demo ./sidecar/server-demo` failed
with "not enough arguments". Pass nil for the new streams parameter
to preserve the prior behavior (NewDefault substitutes SystemIO).
Change-Id: I20227b2355cde7d19e22eba3eb841c6d8611e8a7
343 lines
8.2 KiB
Go
343 lines
8.2 KiB
Go
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
package update
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/larksuite/cli/internal/core"
|
|
"github.com/larksuite/cli/internal/util"
|
|
"github.com/larksuite/cli/internal/validate"
|
|
"github.com/larksuite/cli/internal/vfs"
|
|
)
|
|
|
|
const (
|
|
registryURL = "https://registry.npmjs.org/@larksuite/cli/latest"
|
|
cacheTTL = 24 * time.Hour
|
|
fetchTimeout = 5 * time.Second
|
|
stateFile = "update-state.json"
|
|
maxBody = 256 << 10 // 256 KB
|
|
|
|
)
|
|
|
|
// UpdateInfo holds version update information.
|
|
type UpdateInfo struct {
|
|
Current string `json:"current"`
|
|
Latest string `json:"latest"`
|
|
}
|
|
|
|
// Message returns a concise update notification.
|
|
func (u *UpdateInfo) Message() string {
|
|
return fmt.Sprintf("lark-cli %s available, current %s", u.Latest, u.Current)
|
|
}
|
|
|
|
// pending stores the latest update info for the current process.
|
|
var pending atomic.Pointer[UpdateInfo]
|
|
|
|
// SetPending stores the update info for consumption by output decorators.
|
|
func SetPending(info *UpdateInfo) { pending.Store(info) }
|
|
|
|
// GetPending returns the pending update info, or nil.
|
|
func GetPending() *UpdateInfo { return pending.Load() }
|
|
|
|
// DefaultClient is the HTTP client used for npm registry requests.
|
|
// Override in tests with an httptest server client.
|
|
var DefaultClient *http.Client
|
|
|
|
func httpClient() *http.Client {
|
|
if DefaultClient != nil {
|
|
return DefaultClient
|
|
}
|
|
return &http.Client{
|
|
Timeout: fetchTimeout,
|
|
Transport: util.SharedTransport(),
|
|
}
|
|
}
|
|
|
|
// updateState is persisted to disk for caching.
|
|
type updateState struct {
|
|
LatestVersion string `json:"latest_version"`
|
|
CheckedAt int64 `json:"checked_at"`
|
|
}
|
|
|
|
// CheckCached checks the local cache only (no network). Always fast.
|
|
func CheckCached(currentVersion string) *UpdateInfo {
|
|
if shouldSkip(currentVersion) {
|
|
return nil
|
|
}
|
|
state, _ := loadState()
|
|
if state == nil || state.LatestVersion == "" {
|
|
return nil
|
|
}
|
|
if !IsNewer(state.LatestVersion, currentVersion) {
|
|
return nil
|
|
}
|
|
return &UpdateInfo{Current: currentVersion, Latest: state.LatestVersion}
|
|
}
|
|
|
|
// RefreshCache fetches the latest version from npm and updates the local cache.
|
|
// No-op if the cache is still fresh (< 24h). Safe to call from a goroutine.
|
|
func RefreshCache(currentVersion string) {
|
|
if shouldSkip(currentVersion) {
|
|
return
|
|
}
|
|
state, _ := loadState()
|
|
if state != nil && time.Since(time.Unix(state.CheckedAt, 0)) < cacheTTL {
|
|
return // cache is fresh
|
|
}
|
|
latest, err := fetchLatestVersion()
|
|
if err != nil {
|
|
return
|
|
}
|
|
_ = saveState(&updateState{
|
|
LatestVersion: latest,
|
|
CheckedAt: time.Now().Unix(),
|
|
})
|
|
}
|
|
|
|
func shouldSkip(version string) bool {
|
|
if os.Getenv("LARKSUITE_CLI_NO_UPDATE_NOTIFIER") != "" {
|
|
return true
|
|
}
|
|
// Suppress in CI environments.
|
|
for _, key := range []string{"CI", "BUILD_NUMBER", "RUN_ID"} {
|
|
if os.Getenv(key) != "" {
|
|
return true
|
|
}
|
|
}
|
|
// No version info at all — can't compare.
|
|
if version == "DEV" || version == "dev" || version == "" {
|
|
return true
|
|
}
|
|
// Skip local dev builds (e.g. v1.0.0-12-g9b933f1-dirty from git describe).
|
|
// Only released versions (clean X.Y.Z) should check for updates.
|
|
if !isRelease(version) {
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
// isRelease returns true for published versions: clean semver (1.0.0)
|
|
// and npm prerelease (1.0.0-beta.1, 1.0.0-rc.1).
|
|
// Returns false for git describe dev builds (v1.0.0-12-g9b933f1-dirty).
|
|
var gitDescribePattern = regexp.MustCompile(`-\d+-g[0-9a-f]{7,}`)
|
|
|
|
func isRelease(version string) bool {
|
|
v := strings.TrimPrefix(version, "v")
|
|
if ParseVersion(v) == nil {
|
|
return false
|
|
}
|
|
return !gitDescribePattern.MatchString(v)
|
|
}
|
|
|
|
// --- state file I/O ---
|
|
|
|
func statePath() string {
|
|
return filepath.Join(core.GetConfigDir(), stateFile)
|
|
}
|
|
|
|
func loadState() (*updateState, error) {
|
|
data, err := vfs.ReadFile(statePath())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var s updateState
|
|
if err := json.Unmarshal(data, &s); err != nil {
|
|
return nil, err
|
|
}
|
|
return &s, nil
|
|
}
|
|
|
|
func saveState(s *updateState) error {
|
|
dir := core.GetConfigDir()
|
|
if err := vfs.MkdirAll(dir, 0700); err != nil {
|
|
return err
|
|
}
|
|
data, err := json.Marshal(s)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return validate.AtomicWrite(statePath(), data, 0644)
|
|
}
|
|
|
|
// FetchLatest queries the npm registry and returns the latest published version.
|
|
// This is a synchronous call with timeout, intended for diagnostic commands (doctor).
|
|
func FetchLatest() (string, error) {
|
|
return fetchLatestVersion()
|
|
}
|
|
|
|
// --- npm registry ---
|
|
|
|
type npmLatestResponse struct {
|
|
Version string `json:"version"`
|
|
}
|
|
|
|
func fetchLatestVersion() (string, error) {
|
|
resp, err := httpClient().Get(registryURL)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
return "", fmt.Errorf("npm registry: HTTP %d", resp.StatusCode)
|
|
}
|
|
|
|
body, err := io.ReadAll(io.LimitReader(resp.Body, maxBody))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
var result npmLatestResponse
|
|
if err := json.Unmarshal(body, &result); err != nil {
|
|
return "", err
|
|
}
|
|
if result.Version == "" {
|
|
return "", fmt.Errorf("npm registry: empty version")
|
|
}
|
|
return result.Version, nil
|
|
}
|
|
|
|
// --- semver helpers ---
|
|
|
|
// IsNewer returns true if version a should be considered an update over b.
|
|
//
|
|
// When both parse as semver, standard comparison applies.
|
|
// When b cannot be parsed (e.g. bare commit hash "9b933f1"), any valid a
|
|
// is considered newer — an unparseable local version is assumed outdated.
|
|
// When a cannot be parsed, returns false (can't confirm it's newer).
|
|
func IsNewer(a, b string) bool {
|
|
ap := parseVersionDetail(a)
|
|
bp := parseVersionDetail(b)
|
|
if ap == nil {
|
|
return false // can't confirm remote is newer
|
|
}
|
|
if bp == nil {
|
|
return true // local version unparseable → assume outdated
|
|
}
|
|
for i := 0; i < 3; i++ {
|
|
if ap.core[i] > bp.core[i] {
|
|
return true
|
|
}
|
|
if ap.core[i] < bp.core[i] {
|
|
return false
|
|
}
|
|
}
|
|
return comparePrerelease(ap.prerelease, bp.prerelease) > 0
|
|
}
|
|
|
|
// ParseVersion parses "X.Y.Z" (with optional "v" prefix and pre-release suffix)
|
|
// into [major, minor, patch]. Returns nil on invalid input.
|
|
func ParseVersion(v string) []int {
|
|
parsed := parseVersionDetail(v)
|
|
if parsed == nil {
|
|
return nil
|
|
}
|
|
return []int{parsed.core[0], parsed.core[1], parsed.core[2]}
|
|
}
|
|
|
|
type parsedVersion struct {
|
|
core [3]int
|
|
prerelease string
|
|
}
|
|
|
|
// validPrerelease matches semver pre-release identifiers (dot-separated).
|
|
// Each identifier is either: "0", a non-zero-leading numeric, or alphanumeric with at least one letter/hyphen.
|
|
// Rejects empty identifiers ("1.0.0-"), leading-zero numerics ("1.0.0-01"), etc.
|
|
var validPrerelease = regexp.MustCompile(
|
|
`^(?:0|[1-9]\d*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)` +
|
|
`(?:\.(?:0|[1-9]\d*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*$`)
|
|
|
|
func parseVersionDetail(v string) *parsedVersion {
|
|
v = strings.TrimPrefix(v, "v")
|
|
if idx := strings.Index(v, "+"); idx >= 0 {
|
|
v = v[:idx]
|
|
}
|
|
prerelease := ""
|
|
if idx := strings.Index(v, "-"); idx >= 0 {
|
|
prerelease = v[idx+1:]
|
|
v = v[:idx]
|
|
if prerelease == "" || !validPrerelease.MatchString(prerelease) {
|
|
return nil
|
|
}
|
|
}
|
|
parts := strings.SplitN(v, ".", 3)
|
|
if len(parts) != 3 {
|
|
return nil
|
|
}
|
|
var nums [3]int
|
|
for i, p := range parts {
|
|
if len(p) > 1 && p[0] == '0' {
|
|
return nil // leading zero in core part (e.g. "01.0.0")
|
|
}
|
|
n, err := strconv.Atoi(p)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
nums[i] = n
|
|
}
|
|
return &parsedVersion{core: nums, prerelease: prerelease}
|
|
}
|
|
|
|
func comparePrerelease(a, b string) int {
|
|
if a == "" && b == "" {
|
|
return 0
|
|
}
|
|
if a == "" {
|
|
return 1
|
|
}
|
|
if b == "" {
|
|
return -1
|
|
}
|
|
ap := strings.Split(a, ".")
|
|
bp := strings.Split(b, ".")
|
|
for i := 0; i < len(ap) && i < len(bp); i++ {
|
|
cmp := comparePrereleaseIdentifier(ap[i], bp[i])
|
|
if cmp != 0 {
|
|
return cmp
|
|
}
|
|
}
|
|
switch {
|
|
case len(ap) > len(bp):
|
|
return 1
|
|
case len(ap) < len(bp):
|
|
return -1
|
|
default:
|
|
return 0
|
|
}
|
|
}
|
|
|
|
func comparePrereleaseIdentifier(a, b string) int {
|
|
an, aErr := strconv.Atoi(a)
|
|
bn, bErr := strconv.Atoi(b)
|
|
aNumeric := aErr == nil
|
|
bNumeric := bErr == nil
|
|
switch {
|
|
case aNumeric && bNumeric:
|
|
if an > bn {
|
|
return 1
|
|
}
|
|
if an < bn {
|
|
return -1
|
|
}
|
|
return 0
|
|
case aNumeric:
|
|
return -1
|
|
case bNumeric:
|
|
return 1
|
|
default:
|
|
return strings.Compare(a, b)
|
|
}
|
|
}
|