Documentation
¶
Overview ¶
Package cmdutil provides reusable CLI helper functions for Cobra commands. Both the open-source CLI and private overlays import this package to avoid duplicating flag validation, time parsing, and UX helpers.
Index ¶
- Constants
- Variables
- func ConfirmDelete(cmd *cobra.Command, resourceType, resourceName string) bool
- func DetectNumericTypeError(err error) (flagName, badValue string, ok bool)
- func FlagOrFallback(cmd *cobra.Command, primary string, aliases ...string) string
- func FormatSubcommandSuggestionHint(parent *cobra.Command, suggestions []string, fallback string) string
- func GroupRunE(cmd *cobra.Command, args []string) error
- func HintSubCmd(use, authoredHint string) *cobra.Command
- func IsEnvelopeSourced(cmd *cobra.Command) bool
- func IsHintOnlyCommand(cmd *cobra.Command) bool
- func IsLeafCmd(cmd *cobra.Command) bool
- func IsPluginSourced(cmd *cobra.Command) bool
- func LevenshteinDist(a, b string) int
- func LevenshteinThreshold(nameLen int) int
- func MarkEnvelopeSource(cmd *cobra.Command)
- func MarkPluginSource(cmd *cobra.Command)
- func MergeHardcodedLeaves(dynamicRoot, hardcodedRoot *cobra.Command) *cobra.Command
- func MissingRequiredFlagsError(cmd *cobra.Command, names ...string) error
- func Morph(name string) string
- func MustFlagOrFallback(cmd *cobra.Command, primary string, aliases ...string) (string, error)
- func MustFlagWithHint(cmd *cobra.Command, name, example string) (string, error)
- func MustGetFlag(cmd *cobra.Command, name string) string
- func NormalizeBoolLiteral(s string) (string, bool)
- func OverridePriority(cmd *cobra.Command) int
- func ParseISOTimeToMillis(flagName, value string) (int64, error)
- func SetOverridePriority(cmd *cobra.Command, priority int)
- func SuffixLooksLikeValue(suffix, typ, format string, enum []string) bool
- func SuggestDescendantSubcommands(parent *cobra.Command, candidate string) []string
- func SuggestSubcommands(parent *cobra.Command, candidate string) []string
- func ValidateRequiredFlagWithAliases(cmd *cobra.Command, primary string, aliases ...string) error
- func ValidateRequiredFlags(cmd *cobra.Command, names ...string) error
- func ValidateTimeRange(startMs, endMs int64) error
- func VisibleFlagNames(cmd *cobra.Command) []string
- type CommandResolution
- type FlagFixResult
- type ResolutionReason
Constants ¶
const MaxCommandSuggestions = 3
MaxCommandSuggestions keeps typo recovery concise even for products with a large command surface.
const OverridePriorityAnnotation = "dws.override-priority"
OverridePriorityAnnotation is the cobra.Command.Annotations key used to declare a command's merge-time override priority. Higher values win when same-named leaves collide during merge. Exported so overlays and helpers can reference the same key as the core merge logic without spelling drift.
const SourceAnnotation = "dws.source"
SourceAnnotation records where a command tree came from. Edition overlays use it to distinguish runtime-authored commands from helper fallbacks that happen to share the same top-level product name.
const SourceEnvelope = "envelope"
SourceEnvelope marks a command as authored by the runtime discovery envelope.
const SourcePlugin = "plugin"
SourcePlugin marks a command as an installed plugin extension. Plugin commands are part of the runtime CLI surface, not the embedded base Schema.
Variables ¶
var CommonFlagAliases = map[string]string{
"json": "format json",
"output": "format",
"out": "format",
"o": "format",
"silent": "quiet",
"dry": "dry-run",
"force": "yes",
"f": "yes",
"timeout-seconds": "timeout",
"device-flow": "device",
"deviceflow": "device",
}
CommonFlagAliases maps commonly misused flag names to their correct equivalents.
var FlexTimeLayouts = []string{ time.RFC3339, "2006-01-02T15:04:05Z", "2006-01-02T15:04:05-07:00", "2006-01-02T15:04:05", "2006-01-02 15:04:05", "2006-01-02T15:04", "2006-01-02 15:04", "2006-01-02", "2006/01/02 15:04:05", "2006/01/02", "20060102", }
FlexTimeLayouts is the ordered list of time formats tried by ParseISOTimeToMillis.
Functions ¶
func ConfirmDelete ¶
ConfirmDelete asks for interactive confirmation before destructive operations. Returns true if --yes/-y flag is set or the user types "yes"/"y".
func DetectNumericTypeError ¶
DetectNumericTypeError checks if err is a Cobra/pflag numeric type validation error. Returns the flag name and the bad value if detected.
func FlagOrFallback ¶
FlagOrFallback reads the primary flag; if empty, falls back through alias flags in order, returning the first non-empty value.
func FormatSubcommandSuggestionHint ¶ added in v1.0.60
func FormatSubcommandSuggestionHint(parent *cobra.Command, suggestions []string, fallback string) string
FormatSubcommandSuggestionHint renders bounded suggestions and always keeps the full-list recovery action visible in the same hint.
func GroupRunE ¶
GroupRunE is the reusable handler for navigation-only parent commands. It shows help without arguments and otherwise returns the same structured resolution contract used by pre-parse validation.
func HintSubCmd ¶
HintSubCmd creates a hidden compatibility command for a reviewed wrong path. It keeps hint-only identity while returning the unified typed resolution.
func IsEnvelopeSourced ¶ added in v1.0.16
IsEnvelopeSourced reports whether cmd was authored by the runtime discovery envelope.
func IsHintOnlyCommand ¶ added in v1.0.58
IsHintOnlyCommand reports whether cmd is a hidden compatibility prompt that has no business execution of its own. Reviewed command-path fallbacks may supersede these nodes, but must still reject collisions with real commands.
func IsPluginSourced ¶ added in v1.0.54
IsPluginSourced reports whether cmd came from an installed plugin.
func LevenshteinDist ¶
LevenshteinDist returns the edit distance between two strings.
func LevenshteinThreshold ¶
LevenshteinThreshold returns the max edit distance allowed based on string length.
func MarkEnvelopeSource ¶ added in v1.0.16
MarkEnvelopeSource stamps cmd with runtime discovery provenance.
func MarkPluginSource ¶ added in v1.0.54
MarkPluginSource stamps cmd with installed-plugin provenance.
func MergeHardcodedLeaves ¶ added in v1.0.16
MergeHardcodedLeaves grafts leaves from hardcodedRoot onto dynamicRoot when the same-named path does not already exist. Groups recurse. On leaf conflicts, the dynamic side wins by default because the runtime envelope is authoritative; hardcoded commands are retained as fallback for paths the envelope does not declare.
A hardcoded leaf or group can opt into replacement by carrying a strictly higher OverridePriority than the dynamic command at the same path.
MergeHardcodedLeaves mutates dynamicRoot in place and returns it. Grafted commands are detached from hardcodedRoot so Cobra parent pointers remain correct.
func MissingRequiredFlagsError ¶ added in v1.0.55
MissingRequiredFlagsError formats the unified "missing required flag(s)" error for the given flag names, or returns nil when none are missing. Use this when the caller has already determined which flags are missing (e.g. after alias/env fallback resolution).
func Morph ¶ added in v1.0.56
Morph normalizes a flag spelling to a table-free canonical form so that morphological variants collapse to one key: case is folded, '_', '.' and spaces are treated as '-', and camelCase boundaries become '-'. It is the single shared primitive used both at build time (when the parameter-alias generator intersects concept members with a command's real flags) and at runtime (when pflag's SetNormalizeFunc resolves an emitted name). Keeping one implementation is a hard invariant: if the two diverged, a name the generator believed reducible could fail to resolve at runtime, which is contract drift.
Morph is idempotent and stable on already-canonical names: Morph("limit") == "limit" and Morph("page-size") == "page-size", so applying it to a command's real flags never changes their identity.
func MustFlagOrFallback ¶
MustFlagOrFallback works like FlagOrFallback but returns an error when all flags are empty.
func MustFlagWithHint ¶
MustFlagWithHint returns an error with an explicit usage example when the flag is empty.
func MustGetFlag ¶
MustGetFlag retrieves a string flag value, checking both local and inherited flags.
func NormalizeBoolLiteral ¶ added in v1.0.56
NormalizeBoolLiteral reduces model-friendly boolean spellings to the exact values accepted by an unambiguous --flag=true/false pflag token.
func OverridePriority ¶ added in v1.0.16
OverridePriority returns the override priority annotation value on cmd, or 0 if the annotation is absent or malformed.
func ParseISOTimeToMillis ¶
ParseISOTimeToMillis parses a time string into a millisecond Unix timestamp. Supports RFC3339, UTC Z, timezone-less, space-separated, date-only, and more. When the input lacks an explicit timezone, Asia/Shanghai is assumed.
func SetOverridePriority ¶ added in v1.0.16
SetOverridePriority stamps the override priority annotation on cmd. A positive value asks the merge layer to promote this command over a same-named leaf with a lower (or unset) priority.
func SuffixLooksLikeValue ¶ added in v1.0.27
SuffixLooksLikeValue decides whether a candidate suffix from a glued "--flagsuffix" token plausibly represents a value for a flag's declared type/format/enum. Shared by StickyHandler (PreParse) and SuggestFlagFix (unknown-flag recovery).
typ is a pflag value type string (e.g. "int", "bool", "string"); format is JSON Schema "format" when present (e.g. "date-time"); enum is the schema enum list when present.
func SuggestDescendantSubcommands ¶ added in v1.0.60
SuggestDescendantSubcommands returns bounded relative paths for available descendants whose canonical name or alias exactly matches candidate. It is the reviewed deep-recovery mode used by hierarchical products such as Sheet, where a model may omit an intermediate group (`sheet read` instead of `sheet range read`). Fuzzy ranking remains a sibling concern so a large subtree cannot drown the user in speculative paths.
func SuggestSubcommands ¶ added in v1.0.60
SuggestSubcommands returns at most MaxCommandSuggestions visible canonical child names, ranked by reviewed SuggestFor matches, prefix relevance, edit distance, length delta, and finally canonical name for deterministic ties. Aliases participate in scoring, but recovery always teaches the canonical command name.
func ValidateRequiredFlagWithAliases ¶
ValidateRequiredFlagWithAliases checks that at least one of the primary flag or its aliases is non-empty.
func ValidateRequiredFlags ¶
ValidateRequiredFlags checks that all named string flags are non-empty. Returns a formatted error listing all missing flags, or nil.
func ValidateTimeRange ¶
ValidateTimeRange checks that endMs is strictly after startMs.
func VisibleFlagNames ¶ added in v1.0.27
VisibleFlagNames returns sorted candidate flag names for cmd.Flags() using flagFixCandidate. Intended for agent-facing error recovery (available_flags).
Types ¶
type CommandResolution ¶ added in v1.0.60
type CommandResolution struct {
// contains filtered or unexported fields
}
CommandResolution is the immutable typed projection of a command-token resolution failure. Its constructors normalize suggestions once so the human hint and machine-readable details cannot diverge.
func NewCommandResolution ¶ added in v1.0.60
func NewCommandResolution(parent *cobra.Command, input string, reason ResolutionReason, suggestions []string, authoredHint string) CommandResolution
NewCommandResolution builds a bounded command-resolution result. Callers may pass sibling suggestions from SuggestSubcommands or reviewed deep-path candidates; both are normalized to the same three-item contract. authoredHint 只能承载人工明确的处理方案;通用帮助引导由此处自动补齐。
func NewInputCommandResolution ¶ added in v1.0.60
func NewInputCommandResolution(parent *cobra.Command, input string, suggestions []string) CommandResolution
NewInputCommandResolution classifies input and builds its one normalized human/machine projection. It is the shared entry point for PreParse and direct group execution.
func (CommandResolution) Details ¶ added in v1.0.60
func (r CommandResolution) Details() map[string]any
Details returns a fresh machine-readable payload for the resolution. It always carries the exact bounded suggestions rendered in Hint.
func (CommandResolution) Err ¶ added in v1.0.60
func (r CommandResolution) Err() error
Err projects the resolution through the repository's structured validation error contract.
type FlagFixResult ¶
type FlagFixResult struct {
Suggestion string
AutoFixFlag string
AutoFixValue string
// HasCorrection 仅标记具体纠错候选;通用 --help 引导不算纠错。
HasCorrection bool `json:"-"`
}
FlagFixResult holds the result of SuggestFlagFix analysis.
func SuggestFlagFix ¶
func SuggestFlagFix(cmd *cobra.Command, flagErr error) FlagFixResult
SuggestFlagFix detects flag-value concatenation errors, common flag aliases, and Levenshtein-close typos.
type ResolutionReason ¶ added in v1.0.60
type ResolutionReason string
ResolutionReason is the stable machine-readable classification for a command-token resolution failure.
const ( // ResolutionUnknownSubcommand reports a token that does not resolve to a // child command of the selected parent. ResolutionUnknownSubcommand ResolutionReason = "unknown_subcommand" // ResolutionUnknownShortcut reports an explicit +shortcut token that does // not resolve under a top-level service. ResolutionUnknownShortcut ResolutionReason = "unknown_shortcut" )
func ClassifyCommandResolution ¶ added in v1.0.60
func ClassifyCommandResolution(parent *cobra.Command, input string) ResolutionReason
ClassifyCommandResolution returns the stable reason for an unresolved token. A leading '+' is shortcut syntax only for a top-level service that actually exposes +shortcut children, and only when it does not already name a real child or alias. Keeping this classification beside CommandResolution prevents PreParse and direct Cobra execution from producing different machine contracts for the same input.