mirror of
https://github.com/larksuite/cli.git
synced 2026-07-03 14:02:43 +08:00
The previous default (atomic.Bool zero-value = enabled) meant any *cobra.Command built without first calling configureFlagCompletions leaked into cobra's package-global flagCompletionFunctions map. Bench runs (scripts/bench_build) showed hundreds of KB and thousands of objects retained per Build call. Flip the semantics so the zero-value matches the safe default: - Rename internal var to flagCompletionsEnabled (zero = disabled). - Rename public API to SetFlagCompletionsEnabled / FlagCompletionsEnabled. - Update call sites in cmd/root.go and scripts/bench_build/main.go. - Add cmd.TestBuild_DefaultNoCompletionLeak: asserts that, with no setter call at all, repeated cmd.Build invocations stay under 50 KB and 500 objects per build (observed: ~0.7 KB, 3 objs/build). This closes the gap that let the wrong default ship — every previous test explicitly Set the switch before exercising it. Change-Id: Ifefb04af5fd45eea9676a344a64ad071b6a4cd1a
39 lines
1.3 KiB
Go
39 lines
1.3 KiB
Go
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
package cmdutil
|
|
|
|
import (
|
|
"sync/atomic"
|
|
|
|
"github.com/spf13/cobra"
|
|
)
|
|
|
|
// Cobra keeps completion callbacks in a package-global map keyed by
|
|
// *pflag.Flag with no removal path, so registrations made for a *cobra.Command
|
|
// outlive the command itself. Default to disabled (zero value = false) and let
|
|
// callers that actually serve a completion request opt in via
|
|
// SetFlagCompletionsEnabled(true).
|
|
var flagCompletionsEnabled atomic.Bool
|
|
|
|
// SetFlagCompletionsEnabled toggles whether RegisterFlagCompletion actually
|
|
// registers callbacks with cobra. Typically set once at process start.
|
|
func SetFlagCompletionsEnabled(enabled bool) {
|
|
flagCompletionsEnabled.Store(enabled)
|
|
}
|
|
|
|
// FlagCompletionsEnabled reports the current switch state.
|
|
func FlagCompletionsEnabled() bool {
|
|
return flagCompletionsEnabled.Load()
|
|
}
|
|
|
|
// RegisterFlagCompletion wraps (*cobra.Command).RegisterFlagCompletionFunc
|
|
// and honors the package switch. The underlying error is swallowed to match
|
|
// the `_ = cmd.RegisterFlagCompletionFunc(...)` style already used here.
|
|
func RegisterFlagCompletion(cmd *cobra.Command, flagName string, fn cobra.CompletionFunc) {
|
|
if !flagCompletionsEnabled.Load() {
|
|
return
|
|
}
|
|
_ = cmd.RegisterFlagCompletionFunc(flagName, fn)
|
|
}
|