Documentation
¶
Overview ¶
Package flagutil provides utilities for working with Cobra flags, particularly for handling persistent flags and the Changed() pattern.
Index ¶
- Constants
- func AnnotateBodyFields(cmd *cobra.Command, meta []FlagMeta, bodyFieldPath string, bodyFlags ...string) error
- func AnnotatePromptFlag(cmd *cobra.Command, name string, spec PromptFlagSpec) error
- func AnyFlagsChanged(cmd *cobra.Command, flagNames []string) bool
- func AttachStdinBody(cmd *cobra.Command, bodyFlag string) (bool, error)
- func BuildRequest[T any](cmd *cobra.Command, meta []FlagMeta, bodyFieldPath string, bodyFlagName string) (*T, error)
- func BuildRequestBody[T any](cmd *cobra.Command, flagName string, annotations string, isRequired bool) (*T, error)
- func ClearBodyRequirements(cmd *cobra.Command, meta []FlagMeta, bodyFieldPath string)
- func DerefOrZero[T any](p *T) T
- func DidDryRunRequest(cmd *cobra.Command) bool
- func FlagChanged(cmd *cobra.Command, name string) bool
- func GetBoolFlag(cmd *cobra.Command, name string) (bool, bool)
- func GetFloat64Flag(cmd *cobra.Command, name string) (float64, bool)
- func GetInt64Flag(cmd *cobra.Command, name string) (int64, bool)
- func GetIntFlag(cmd *cobra.Command, name string) (int, bool)
- func GetStringArrayFlag(cmd *cobra.Command, name string) ([]string, bool)
- func GetStringFlag(cmd *cobra.Command, name string) (string, bool)
- func GetStringSliceFlag(cmd *cobra.Command, name string) ([]string, bool)
- func HasAnyFlagWithPrefix(cmd *cobra.Command, prefix string) bool
- func HasStdinInput(cmd *cobra.Command) bool
- func MarkBodyFlag(cmd *cobra.Command, name string) error
- func MarkDryRunRequest(cmd *cobra.Command)
- func MergeInputIntoBody(cmd *cobra.Command, bodyFlagName, key, input string, value any) error
- func MergeOperationDeclaredInputs(cmd *cobra.Command, bodyFlags []string, canonicalBodyFlag string, ...) error
- func MergePresetBody(body string, m PresetMerge) (string, error)
- func MergePresetObject(user map[string]json.RawMessage, m PresetMerge) error
- func OverridePromptRequirement(cmd *cobra.Command, name string, required, promptOptional bool) error
- func PrimeDispatchBody(cmd *cobra.Command, bodyFlag string) (bool, error)
- func ReadStdinBody(cmd *cobra.Command, bodyFlag string) ([]byte, error)
- func RegisterFlags(cmd *cobra.Command, meta []FlagMeta)
- func ResolveBodyFlag(cmd *cobra.Command, flagName string) error
- func ResolveBodyFlagValue(cmd *cobra.Command, flagName, val string) (string, error)
- func ResolveOutputFormat(cmd *cobra.Command, configured string, agentMode bool) string
- func SetMetaPromptOptional(cmd *cobra.Command, meta []FlagMeta, promptOptional bool)
- func SetPromptOptional(cmd *cobra.Command, name string, promptOptional bool) error
- func SetStdinReadDeadline(enabled bool)
- func SpacedBoolValueHint(cmd *cobra.Command, args []string) string
- func ValidateEnumFlag(cmd *cobra.Command, name string, allowed []string) error
- func ValidateMeta[T any](meta []FlagMeta) error
- func ValidateServerURL(value string) error
- func WithCLIValidation(err error) error
- type DispatchError
- type DispatchInput
- type DispatchKey
- type DispatchRoute
- type DispatchTable
- type FlagKind
- type FlagMeta
- type MissingRequiredFieldError
- type MissingRequiredFlagError
- type PresetConflictError
- type PresetMerge
- type PromptFlagSpec
- type StdinTimeoutError
- type UnionMeta
- type UnionVariantMeta
Constants ¶
const ( AnnotationRequired = "speakeasy:required" AnnotationEnv = "speakeasy:env" AnnotationConfig = "speakeasy:config" AnnotationDefaultResolves = "speakeasy:default-resolves" AnnotationBodyField = "speakeasy:body-field" AnnotationBodyFlag = "speakeasy:body-flag" AnnotationDocSurface = "speakeasy:doc-surface" AnnotationPrompt = "speakeasy:prompt" AnnotationPromptDirect = "speakeasy:prompt-direct" AnnotationPromptLabel = "speakeasy:prompt-label" AnnotationPromptKind = "speakeasy:prompt-kind" AnnotationPromptValues = "speakeasy:prompt-values" AnnotationPromptOrder = "speakeasy:prompt-order" AnnotationUnionMember = "speakeasy:union-member" AnnotationOpDeclaredInput = "speakeasy:op-declared-input" )
const AnnotationWholeBodyFlag = "speakeasy_whole_body_flag"
Variables ¶
This section is empty.
Functions ¶
func AnnotateBodyFields ¶ added in v0.1.68
func AnnotatePromptFlag ¶ added in v0.1.68
func AnnotatePromptFlag(cmd *cobra.Command, name string, spec PromptFlagSpec) error
func AnyFlagsChanged ¶
AnyFlagsChanged checks if any of the given flags were changed. This is useful for checking if any request-shaping flags were set (for stdin mutual exclusion).
func AttachStdinBody ¶ added in v0.1.68
func BuildRequest ¶
func BuildRequest[T any](cmd *cobra.Command, meta []FlagMeta, bodyFieldPath string, bodyFlagName string) (*T, error)
BuildRequest reads all flags described by meta, validates them, and populates a new T. Returns a pointer to the populated struct. Union fields are handled automatically via their embedded UnionMeta.
bodyFieldPath identifies which field on T contains the request body (e.g. "BaseUser"). When the --body flag or stdin is piped, the JSON is unmarshaled into that sub-field first, then individual flags override specific fields (merge behavior). Empty string means the entire struct is the body (IsRequestBody path) or there is no body field (params-only).
bodyFlagName is the name of the whole-body JSON flag (e.g. "body"). When non-empty and the flag is set, its value takes priority over stdin. Individual flags always override both.
func BuildRequestBody ¶
func BuildRequestBody[T any](cmd *cobra.Command, flagName string, annotations string, isRequired bool) (*T, error)
BuildRequestBody reads a request body from a flag or stdin, unmarshals JSON, and returns *T. This handles the IsRequestBody pattern where the entire body is a single JSON blob. When isRequired is false and no input is provided, returns (nil, nil) instead of an error.
func ClearBodyRequirements ¶ added in v0.1.68
func DerefOrZero ¶
func DerefOrZero[T any](p *T) T
DerefOrZero safely dereferences a pointer, returning the zero value if nil. Used for optional request bodies with reference types ([]byte, slices, maps) where BuildRequestBody returns *T but the SDK method takes T.
func DidDryRunRequest ¶ added in v0.1.68
func FlagChanged ¶
FlagChanged checks if a flag was explicitly set by the user. This correctly handles both local flags and inherited persistent flags. IMPORTANT: Use this instead of cmd.Flags().Changed() which doesn't reliably detect changes on inherited persistent flags.
func GetBoolFlag ¶
GetBoolFlag returns the value of a bool flag and whether it was changed. This correctly handles both local flags and inherited persistent flags.
func GetFloat64Flag ¶
GetFloat64Flag returns the value of a float64 flag and whether it was changed. This correctly handles both local flags and inherited persistent flags.
func GetInt64Flag ¶
GetInt64Flag returns the value of an int64 flag and whether it was changed. This correctly handles both local flags and inherited persistent flags.
func GetIntFlag ¶
GetIntFlag returns the value of an int flag and whether it was changed. This correctly handles both local flags and inherited persistent flags.
func GetStringArrayFlag ¶
GetStringArrayFlag returns the value of a string array flag and whether it was changed. This correctly handles both local flags and inherited persistent flags.
func GetStringFlag ¶
GetStringFlag returns the value of a string flag and whether it was changed. This correctly handles both local flags and inherited persistent flags.
func GetStringSliceFlag ¶
GetStringSliceFlag returns the value of a string slice flag and whether it was changed. This correctly handles both local flags and inherited persistent flags. StringSlice supports both comma-separated ("a,b") and repeated ("--f a --f b") syntax.
func HasAnyFlagWithPrefix ¶
HasAnyFlagWithPrefix checks if any flag with the given prefix was changed. This is useful for detecting if any field in a nested object or union variant was set.
func HasStdinInput ¶
HasStdinInput checks if there is data available on stdin. It accepts a cobra.Command to support cmd.SetIn() for testing, falling back to os.Stdin.Stat() for production pipe detection.
func MarkDryRunRequest ¶ added in v0.1.68
func MergeInputIntoBody ¶ added in v0.1.68
bodyFlagName is "" when the body was attached from stdin by AttachStdinBody.
func MergeOperationDeclaredInputs ¶ added in v0.1.68
func MergePresetBody ¶ added in v0.1.68
func MergePresetBody(body string, m PresetMerge) (string, error)
func MergePresetObject ¶ added in v0.1.68
func MergePresetObject(user map[string]json.RawMessage, m PresetMerge) error
func OverridePromptRequirement ¶ added in v0.1.68
func PrimeDispatchBody ¶ added in v0.1.68
func ReadStdinBody ¶ added in v0.1.68
ReadStdinBody returns nil, nil when stdin is a TTY.
func RegisterFlags ¶
RegisterFlags registers Cobra flags from metadata, including union flags. Flags that already exist as inherited persistent flags (e.g., global security credentials) are skipped to prevent local flags from shadowing them.
func ResolveBodyFlag ¶ added in v0.1.68
Valid JSON never begins with '@', so re-resolving the stored value is a no-op.
func ResolveBodyFlagValue ¶ added in v0.1.68
func ResolveOutputFormat ¶ added in v0.1.68
func SetMetaPromptOptional ¶ added in v0.1.68
func SetPromptOptional ¶ added in v0.1.68
func SetStdinReadDeadline ¶ added in v0.1.68
func SetStdinReadDeadline(enabled bool)
func SpacedBoolValueHint ¶ added in v0.1.68
func ValidateEnumFlag ¶ added in v0.1.68
func ValidateMeta ¶
ValidateMeta checks that all FieldPaths in meta resolve to valid fields on T. Call from RegisterFlags or init() to catch template generation bugs at startup rather than at CLI runtime.
func ValidateServerURL ¶ added in v0.1.68
func WithCLIValidation ¶ added in v0.1.68
Types ¶
type DispatchError ¶ added in v0.1.68
func (*DispatchError) CLIReason ¶ added in v0.1.68
func (*DispatchError) CLIReason() string
func (*DispatchError) Error ¶ added in v0.1.68
func (e *DispatchError) Error() string
func (*DispatchError) Unwrap ¶ added in v0.1.68
func (e *DispatchError) Unwrap() error
type DispatchInput ¶ added in v0.1.68
type DispatchKey ¶ added in v0.1.68
type DispatchRoute ¶ added in v0.1.68
type DispatchRoute struct {
ID string
Label string
SelectorFlag string
Default bool
PresetJSON string
PresetMerge PresetMerge
}
func Select ¶ added in v0.1.68
func Select(cmd *cobra.Command, args []string, table DispatchTable) (*DispatchRoute, error)
type DispatchTable ¶ added in v0.1.68
type DispatchTable struct {
Command string
BodyFlag string
Escape string
Routes []DispatchRoute
Inputs []DispatchInput
Keys []DispatchKey
}
type FlagKind ¶
type FlagKind int
FlagKind describes what kind of value a flag carries.
const ( FlagKindString FlagKind = iota // string flag → string field FlagKindBool // bool flag → bool field FlagKindInt64 // int64 flag → int64 field FlagKindFloat64 // float64 flag → float64 field FlagKindStringArray // string array flag → []string field FlagKindDateTime // string flag → validated as RFC3339, stored as time.Time or string FlagKindDate // string flag → validated as date, stored as types.Date or string FlagKindEnum // string flag → named enum type (reflect.Convert) FlagKindIntEnum // string flag → parse int → named int enum type FlagKindJSON // string flag → unmarshal into struct FlagKindUnion // union field — handled via UnionMeta FlagKindFile // string flag (file path) → read file → populate Content/FileName struct FlagKindFileArray // string flag (comma-separated file paths) → read files → populate []FileStruct FlagKindBytes // string flag → "file:<path>" reads file, "b64:<data>" base64-decodes, else raw UTF-8 bytes → []byte field )
type FlagMeta ¶
type FlagMeta struct {
// Flag identity
FlagName string // Cobra flag name, e.g. "request-body.emoji"
Shorthand string // Single-letter shorthand for Cobra (e.g. "s" for -s), empty if none
FieldPath string // Dot-delimited Go struct path, e.g. "RequestBody.Emoji"
Kind FlagKind // What type of flag this is
// Flag behavior
Optional bool // true if Go field is a pointer type
Required bool // true if user must provide this flag
HasDefault bool // true if optional+has-default (apply cobra default when flag unchanged and no body/stdin)
// Validation
EnumValues []string // valid values for enum validation; nil if not enum
MinLength int64 // schema minLength for string flags (0 = unconstrained)
HasMinimum bool // schema minimum declared for numeric flags
Minimum float64 // schema minimum (valid when HasMinimum)
HasMaximum bool // schema maximum declared for numeric flags
Maximum float64 // schema maximum (valid when HasMaximum)
// JSON unmarshal
Annotations string // struct tag for JSON unmarshal, e.g. `request:"mediaType=application/json"`
// Union support
Union *UnionMeta // non-nil when Kind == FlagKindUnion
// Registration (used by RegisterFlags)
Description string // help text for Cobra
DefaultStr string // default for String/Enum/DateTime/JSON flags
DefaultBool bool // default for Bool flags
DefaultInt int64 // default for Int64 flags
DefaultFloat float64 // default for Float64 flags
// Display grouping (used by help template)
Group string // optional group label for organizing flags in --help output
// Value resolution (used by interactive prompting to skip already-resolved flags)
EnvVar string // environment variable name, e.g. "MYAPP_API_KEY"; empty if none
ConfigKey string // config file key, e.g. "api_key"; empty if none
}
FlagMeta describes a single CLI flag and how it maps to a request struct field. This is the single source of truth — used for both Cobra flag registration (RegisterFlags) and request building (BuildRequest). This code is designed for CLI startup, not hot paths.
func NonBodyMeta ¶ added in v0.1.68
type MissingRequiredFieldError ¶ added in v0.1.68
func (*MissingRequiredFieldError) CLIReason ¶ added in v0.1.68
func (*MissingRequiredFieldError) CLIReason() string
func (*MissingRequiredFieldError) Error ¶ added in v0.1.68
func (e *MissingRequiredFieldError) Error() string
type MissingRequiredFlagError ¶ added in v0.1.68
type MissingRequiredFlagError struct {
FlagName string
Detail string // optional suffix, e.g. "(or provide via stdin)"
}
func (*MissingRequiredFlagError) CLIReason ¶ added in v0.1.68
func (*MissingRequiredFlagError) CLIReason() string
func (*MissingRequiredFlagError) Error ¶ added in v0.1.68
func (e *MissingRequiredFlagError) Error() string
type PresetConflictError ¶ added in v0.1.68
type PresetConflictError struct {
Command string
Variant string
Key string
Value string // JSON text of the conflicting discriminator value ("" for a foreign key)
Escape string
}
func (*PresetConflictError) CLIReason ¶ added in v0.1.68
func (*PresetConflictError) CLIReason() string
func (*PresetConflictError) Error ¶ added in v0.1.68
func (e *PresetConflictError) Error() string
type PresetMerge ¶ added in v0.1.68
type PresetMerge struct {
Command string
Variant string
Preset string
Foreign []string // selector keys declared only by other union members
DiscriminatorKey string
DiscriminatorValue string
DiscriminatorAliases []string // every discriminator value (JSON text) selecting the pinned variant
Escape string
}
type PromptFlagSpec ¶ added in v0.1.68
type StdinTimeoutError ¶ added in v0.1.68
type StdinTimeoutError struct {
BodyFlag string
}
func (*StdinTimeoutError) CLIReason ¶ added in v0.1.68
func (*StdinTimeoutError) CLIReason() string
func (*StdinTimeoutError) Error ¶ added in v0.1.68
func (e *StdinTimeoutError) Error() string
type UnionMeta ¶
type UnionMeta struct {
Discriminated bool // true for discriminated, false for non-discriminated
DiscriminatorKey string // Go field name for discriminator on variant structs (e.g. "Type")
Optional bool // true if the union field itself is *T (pointer)
TypeDescription string // help text for top-level JSON flag
Variants []UnionVariantMeta // variant definitions (empty for non-discriminated)
VariantKeys []string // distinguishing selector keys across variants (e.g. ["card","bank_transfer"])
DefaultJSON string // JSON object merged when no VariantKeys key is present
}
UnionMeta describes a union field's structure for metadata-driven registration and parsing.
type UnionVariantMeta ¶
type UnionVariantMeta struct {
DiscriminatorValue string // discriminator value, e.g. "circle"
FlagName string // full flag name, e.g. "shape-request.shape.circle"
FieldName string // Go field name on union struct, e.g. "Circle"
CanExpand bool // whether variant has expanded field flags
Description string // help text for variant JSON flag
Fields []FlagMeta // variant leaf fields (FieldPath relative to variant struct)
}
UnionVariantMeta describes a single variant within a discriminated union.