Documentation
¶
Overview ¶
Package spec builds and validates command schemas from application structs.
Index ¶
- Constants
- Variables
- func AncestorShadowError(descendant FlagOwner, declaration string, ancestor FlagOwner) error
- func BootstrapFeatureConflictError() error
- func BootstrapFieldTypeError() error
- func BootstrapReadsWhileParsingError() error
- func BootstrapRequiresBootstrapperError() error
- func BootstrapTagged(tag reflect.StructTag) bool
- func BuiltinRequested(chain []*Command, tokens []tokenizer.Token) bool
- func BuiltinShortConflictError(builtin string, short rune, flagName string) error
- func BuiltinShortPairError(short rune) error
- func CanNegate(flagSpec *Flag) bool
- func CascadingRequiresMultiError(flagName string) error
- func Complete(rootCmd *Command, args []string, opts CompleteOptions) predict.Result
- func CompletionRequiresEnableError() error
- func ConfigExplicitConflictError() error
- func ConfigKeyPath(flag *Flag, chain []*Command) string
- func DefaultArgName(fieldName string, tag reflect.StructTag) string
- func DefaultOnOneOfFlagError() error
- func DefaultOnRequiredFlagError() error
- func DefaultTypeHelp(targetType reflect.Type, tags FieldTags) string
- func DeprecatedOnRequiredFlagError() error
- func DescribeFeatureExpression(featureExpr string) string
- func DuplicateFeatureError(name string, typeName string) error
- func FailingFeatureTerms(featureExpr string, activeFeatures map[string]bool) []string
- func FeatureEnvCollisionError(envVar string, first string, second string) error
- func FeatureEnvModeConflictError() error
- func FeatureFieldDeclaresEnv(tag reflect.StructTag) bool
- func FeatureFieldEnvWithContainerEnvError(fieldName string) error
- func FeatureFieldName(fieldName string, tag reflect.StructTag) (string, error)
- func FeatureFieldTypeError(fieldName string, typeName string) error
- func FeatureOnRequiredFlagError() error
- func FeatureStageAllOrNothingError(fieldName string) error
- func FeatureTagRequiresEnableError() error
- func FeaturesAlreadyDeclaredError(firstFlagName string) error
- func FeaturesMustBeOnRootError() error
- func FeaturesMustBeStructParameterError() error
- func FeaturesRequiresEnableError() error
- func FieldTagKeys(tagSpecs []TagSpec) []string
- func FlagTokenResolves(chain []*Command, tok tokenizer.Token) bool
- func FloatBoundParser(bitSize int) func(string) (float64, error)
- func GroupTagOnRequiredFlagError(tag string) error
- func ImplicitCommandAlreadyDeclaredError(firstFieldName string) error
- func ImplicitFlagDepth(chain []*Command, tokens []tokenizer.Token) int
- func IsBuiltinFlag(flagSpec *Flag) bool
- func IsBuiltinShortFlag(flagSpec *Flag) bool
- func IsReservedPredictorName(name string) bool
- func MatchFeature(featureExpr string, activeFeatures map[string]bool) bool
- func NormalizeFeatureExpression(featureExpr string) string
- func OneOfAndOverlapError(oneOfGroup, andGroup, firstFlag, secondFlag string) error
- func ParseFeatureContainerEnv(containerTag reflect.StructTag) ([]string, bool)
- func ParseFeatureTag(feature string, required bool) (string, error)
- func ParseFlagShort(tag reflect.StructTag) rune
- func ParseGlobPatterns(value string) ([]string, error)
- func ParseStrictBoolTag(tag reflect.StructTag, key string) (bool, bool, error)
- func ParseStrictStringTag(tag reflect.StructTag, tagSpec TagSpec) (string, bool, error)
- func ParseSummaryTag(tag reflect.StructTag, defaultSummary string) (string, error)
- func ProcessFeaturesField(builder any, structField reflect.StructField, fieldHandle any, ...) error
- func ProjectTextValue[T cmp.Ordered](elemType reflect.Type, value reflect.Value) (T, bool)
- func ResolveFlagEnvVars(tag reflect.StructTag, flagName string, envPrefix string) ([]string, bool)
- func RoutingFlagConsumesNext(chain []*Command, tok tokenizer.Token) bool
- func RoutingLeadingShortRegistered(chain []*Command, tok tokenizer.Token) bool
- func SingleMemberGroupError(kind, group, flagName, suggestion string) error
- func SplitTagList(tag reflect.StructTag, key string) []string
- func TagCandidatesForRole(role string) ([]string, bool)
- func TerminalImplicitLevels(chain []*Command, tokens []tokenizer.Token, terminatorOperands bool) int
- func TextRangeParser[T cmp.Ordered](elemType reflect.Type) (func(string) (T, error), bool)
- func TrailingCollectorAlreadyDeclaredError(containerName, firstFieldName string) error
- func ValidateBranchGrammar(grammar BranchGrammar) error
- func ValidateConfigFileConfigTag(tag reflect.StructTag) error
- func ValidateCountRangeSpec(spec *Range, tagName string) error
- func ValidateCounterDefaultTag(tag reflect.StructTag) error
- func ValidateFeatureEnvSurfaces(containerTag reflect.StructTag, envDeclarer string) error
- func ValidateFeatureExpression(featureExpr string) error
- func ValidateFeatureFieldTags(field *FeatureField, tag reflect.StructTag) error
- func ValidateFeatureReferences(root *Command) error
- func ValidateFieldTags(tag reflect.StructTag, role string, candidates []string, ...) error
- func ValidateImplicitFeature(tag reflect.StructTag) error
- func ValidateNonContainerFieldTags(tag reflect.StructTag, fieldTagKeys []string, opts ValidationOptions) error
- func ValidatePredictorTag(tag reflect.StructTag, isBool bool, registeredNames []string, ...) error
- func ValidateScalarRange[T cmp.Ordered](rangeSpec *Range, boundKind string, parse func(string) (T, error)) error
- func ValidateTextBounds(rangeSpec *Range, boundKind string, validate func(string) error) error
- func ValidateTrailingGrammar(grammar TrailingGrammar) error
- func VersionJSONShadowError(descendant FlagOwner, ancestor FlagOwner) error
- func XorAndOverlapError(xorGroup, andGroup, firstFlag, secondFlag string) error
- type Arg
- type BranchGrammar
- type Command
- func (c *Command) CompletionFlagVisible(isRoot bool) bool
- func (c *Command) FeatureNames() []string
- func (c *Command) FindFeature(name string) *FeatureField
- func (c *Command) FindFlag(name string) *Flag
- func (c *Command) FindShortFlag(r rune) *Flag
- func (c *Command) FindSubcommand(name string) *Command
- func (c *Command) HasCompletionCommand() bool
- func (c *Command) HasUserSubcommands() bool
- func (c *Command) ImplicitCommand() *Command
- func (c *Command) InheritBuiltinVisibilityFrom(src *Command)
- func (c *Command) VersionFlagVisible(isRoot bool) bool
- func (c *Command) WhyFlagVisible() bool
- func (c *Command) WhyFormats() []string
- type CompleteOptions
- type CompletionAnalysis
- type ConfigSettings
- type DashArgs
- type FeatureField
- type FieldTags
- type Flag
- type FlagOwner
- type GroupCensus
- type KeyCase
- type Options
- type PredictorKind
- type PredictorSpec
- type Range
- type RangeDomain
- type RawArgs
- type ShorthandStep
- type ShorthandWalk
- type SingleMemberGroup
- type TagKind
- type TagSpec
- type TagSpecProvider
- type TrailingArgGrammar
- type TrailingGrammar
- type ValidationOptions
Constants ¶
const ( // DefaultHelpFlagHelp is the description of the built-in --help flag. It is // the single source rendered on help screens, completion candidates, and // the shared built-in row of synthesized commands. DefaultHelpFlagHelp = "Show help" // DefaultHelpCommandHelp is the default description for the help subcommand. DefaultHelpCommandHelp = "Show help for a command" // DefaultVersionFlagHelp is the description of the built-in --version flag, // the single source rendered on help screens and completion candidates. DefaultVersionFlagHelp = "Show version" // DefaultVersionCommandHelp is the default description for the version // subcommand; it stays richer than the flag's row because the command list // has room for the full phrase. DefaultVersionCommandHelp = "Show version information" // DefaultCompletionCommandHelp is the default description for the completion subcommand. DefaultCompletionCommandHelp = "Generate shell completion scripts" // DefaultCompletionFlagHelp is the default description for the --completion flag. DefaultCompletionFlagHelp = "Generate shell completion script" // DefaultWhyFlagHelp is the default description for the --why flag. // Accepted output formats are advertised structurally — as a value slot // and enum hint in help, and as completion candidates — only when the app // enabled more than the default text format. DefaultWhyFlagHelp = "Show resolved field values and where they came from (values redacted unless tagged safe)" // WhyFormatText is the default --why output format. WhyFormatText = "text" // WhyFormatJSON is the machine-readable --why output format, available // only when the app enabled app.EnableWhy(conga.WhyOptionJSON()). WhyFormatJSON = "json" // VersionJSONFlagName is the engine-owned name of the opt-in version // command's machine-readable output selector. Schema building synthesizes // the flag with this name and binding matches the synthesized spec by // identity, so the two sites stay coupled through one source of truth. VersionJSONFlagName = "json" )
const ( FeatureStageAlpha = "alpha" FeatureStageBeta = "beta" FeatureStageGA = "ga" FeatureStageDeprecated = "deprecated" )
Feature stage vocabulary of the stage struct tag, mirroring Kubernetes' feature maturity levels. The stage is declared per feature field; when any field declares one, every field must.
Variables ¶
var ( // BuiltinHelpFlag is the shared definition for the standard --help flag. BuiltinHelpFlag = &Flag{Name: "help", Help: DefaultHelpFlagHelp, IsBool: true} // BuiltinVersionFlag is the shared definition for the standard --version flag. BuiltinVersionFlag = &Flag{Name: "version", Help: DefaultVersionFlagHelp, IsBool: true} // BuiltinCompletionFlag is the shared definition for the standard --completion flag. // Shell candidates are resolved through the completion-enabled "shell" // predictor (the same predictor the `completion <shell>` argument uses), so // the supported-shell list is never referenced from schema-building code. BuiltinCompletionFlag = &Flag{ Name: "completion", Help: DefaultCompletionFlagHelp, Placeholder: "SHELL", Predictor: &PredictorSpec{Kind: PredictorKindCustom, Name: "shell"}, } // BuiltinWhyFlag is the shared definition for the standard --why flag. BuiltinWhyFlag = &Flag{Name: "why", Help: DefaultWhyFlagHelp, IsBool: true} )
var ( // ErrSchema indicates the command schema could not be built from the target struct. ErrSchema = errors.New("schema error") // ErrInvalidTarget indicates the schema target is not a pointer to a struct. ErrInvalidTarget = fmt.Errorf("%w: target must be a pointer to a struct", ErrSchema) // ErrDuplicateFlag indicates a duplicate flag name or short flag rune was defined. ErrDuplicateFlag = fmt.Errorf("%w: duplicate flag", ErrSchema) // ErrDuplicateDeclaration indicates a duplicate declaration other than a // flag: a subcommand name or alias, a trailing-argument collector, a // Features container, or a feature name. Messages name what is duplicated // right after it ("duplicate subcommand \"deploy\" ..."). ErrDuplicateDeclaration = fmt.Errorf("%w: duplicate", ErrSchema) // ErrInvalidArgOrder indicates an invalid positional argument order. ErrInvalidArgOrder = fmt.Errorf("%w: invalid positional argument order", ErrSchema) // ErrInvalidRangeSyntax indicates an invalid syntax was provided for a range, len, or items tag. ErrInvalidRangeSyntax = fmt.Errorf("%w: invalid range syntax", ErrSchema) // ErrInvalidConfigFilePlacement indicates a ConfigFile field was declared on a subcommand struct. ErrInvalidConfigFilePlacement = fmt.Errorf("%w: ConfigFile can only be declared on the root command", ErrSchema) // ErrInvalidStructTag indicates a malformed struct tag was encountered. ErrInvalidStructTag = fmt.Errorf("%w: invalid struct tag", ErrSchema) )
Schema error sentinels.
Functions ¶
func AncestorShadowError ¶ added in v0.9.0
AncestorShadowError builds the error for a flag name, alias, or short rune (declaration, such as "--verbose", "alias --v", or "short flag -v") that a descendant command redeclares from an ancestor. Both sides are named by struct and field. The runtime schema builder and the static analyzer share it as the single source of truth.
func BootstrapFeatureConflictError ¶
func BootstrapFeatureConflictError() error
BootstrapFeatureConflictError builds the schema error for a bootstrap field that is also feature-gated. The bootstrap phase runs before feature gates resolve, so a gated bootstrap field cannot be evaluated reliably.
func BootstrapFieldTypeError ¶
func BootstrapFieldTypeError() error
BootstrapFieldTypeError builds the schema error for a bootstrap field whose type is not a pure scalar value. Restricting bootstrap fields to scalar, slice, and map shapes keeps the second coercion cheap and free of I/O.
func BootstrapReadsWhileParsingError ¶ added in v0.9.0
func BootstrapReadsWhileParsingError() error
BootstrapReadsWhileParsingError builds the schema error for a bootstrap field typed conga.FileContent (or a slice or map of it). Bootstrap fields are coerced in two passes, and FileContent reads its file, or stdin, each time.
func BootstrapRequiresBootstrapperError ¶ added in v0.3.0
func BootstrapRequiresBootstrapperError() error
BootstrapRequiresBootstrapperError builds the schema error for a bootstrap-tagged field under a command hierarchy that never implements conga.Bootstrapper. The runtime schema builder and the static analyzer share it as the single source of truth.
func BootstrapTagged ¶
BootstrapTagged reports whether the bootstrap tag is declared with an accepted presence-or-true value. The runtime schema builder and the static analyzer share it as the single source of truth.
func BuiltinRequested ¶ added in v0.6.0
BuiltinRequested reports whether tokens request a built-in rendering flag visible on chain before the -- terminator.
func BuiltinShortConflictError ¶ added in v0.4.0
BuiltinShortConflictError builds the schema error for a user-declared short flag rune that claims the rune assigned to a built-in flag the command offers: the binder would keep the user flag while the help screen still advertises the rune for the built-in. The runtime schema builder and the static analyzer share it as the single source of truth.
func BuiltinShortPairError ¶ added in v0.4.0
BuiltinShortPairError builds the schema error for app.HelpShortFlag and app.VersionShortFlag claiming the same rune while both built-ins are offered: the binder registers --help first, so the --version rune would be dropped while both flag rows still advertise it. The runtime schema builder and the static analyzer share it as the single source of truth.
func CanNegate ¶
CanNegate reports whether flagSpec may be re-bound by a `no-`-prefixed token: only boolean negatable flags qualify. Every `no-` retry path (binder token parsing, flag-index lookup, and completion consumption) funnels through this guard so a `no-` token can never consume an unrelated flag.
func CascadingRequiresMultiError ¶
CascadingRequiresMultiError builds the cascading⟹multi arity-guard error for a root config-file flag: a flag without multi:"true" cannot report every merged file under Cascading(). The error wraps ErrSchema so runtime schema validation returns it directly and the static analyzer reports it verbatim, keeping the lint-time and runtime messages a single source of truth.
func Complete ¶
func Complete(rootCmd *Command, args []string, opts CompleteOptions) predict.Result
Complete evaluates command-line arguments up to the cursor against the AST Command tree and returns the resolved Result containing completion items and shell directives.
func CompletionRequiresEnableError ¶
func CompletionRequiresEnableError() error
CompletionRequiresEnableError builds the completion⟹enable schema guard: a command struct that declares a CompletionCommand field while completion is disabled would have the field silently dropped, so schema build rejects it and names the missing opt-in. The error wraps ErrSchema so runtime schema validation returns it directly and the static analyzer reports it verbatim, keeping the lint-time and runtime messages a single source of truth.
func ConfigExplicitConflictError ¶
func ConfigExplicitConflictError() error
ConfigExplicitConflictError builds the error when ConfigExplicit is combined with ConfigPaths or ConfigCascading. The error wraps ErrSchema so runtime schema validation returns it directly and the static analyzer reports it verbatim, keeping the lint-time and runtime messages a single source of truth.
func ConfigKeyPath ¶ added in v0.9.0
ConfigKeyPath returns the one config key path that sets flag, spelled as a config file writes it: the owning commands' section names in the app's key case, then the flag's config tag as written, or its name in the key case when it has no tag. A tag that already starts with the owning command path names that path itself and is not prefixed twice. chain runs from the root command, which carries the key case, to the command declaring flag.
func DefaultArgName ¶ added in v0.6.0
DefaultArgName returns the positional-argument display name used in usage syntax and diagnostics: the name tag when present, else the angle-bracketed kebab-case struct field name. The runtime schema builder and the static analyzer share it as the single source of truth.
func DefaultOnOneOfFlagError ¶ added in v0.4.0
func DefaultOnOneOfFlagError() error
DefaultOnOneOfFlagError builds the schema error for a default tag on a oneof member: the default marks the member as set in Get/IsSet and in --why without satisfying the Changed()-based exactly-one group, so the flag would look chosen while validation still demands a choice. The runtime schema builder and the static analyzer share it as the single source of truth.
func DefaultOnRequiredFlagError ¶ added in v0.4.0
func DefaultOnRequiredFlagError() error
DefaultOnRequiredFlagError builds the schema error for a default tag on a required flag: a default would satisfy the requirement without any caller input, making the requirement meaningless. The runtime schema builder and the static analyzer share it as the single source of truth.
func DefaultTypeHelp ¶
DefaultTypeHelp returns the default help text contributed by a flag or argument's value type. Custom domain types may implement Help(FieldTags) to self-describe their accepted value format, tailored to the field's declared tags (e.g. File with existing + stdin yields "Path to an existing file or '-' for stdin"). Pointer, slice, and map wrappers are unwrapped so the repeated value's help is used, and "" is reported when the type contributes no help.
func DeprecatedOnRequiredFlagError ¶ added in v0.4.0
func DeprecatedOnRequiredFlagError() error
DeprecatedOnRequiredFlagError builds the schema error for a deprecated tag on a required flag: callers cannot migrate away from a flag they are still forced to supply. The runtime schema builder and the static analyzer share it as the single source of truth.
func DescribeFeatureExpression ¶ added in v0.9.0
DescribeFeatureExpression renders a feature expression as the phrase that follows "requires" in gate diagnostics:
x feature "x" !x feature "x" to be off a,b features "a" and "b" !a,!b features "a" and "b" to be off a,!b feature "a" on and "b" off a,b,!c features "a" and "b" on and "c" off
Terms keep their expression order within the on and off groups. Invalid terms are skipped, as in NormalizeFeatureExpression.
func DuplicateFeatureError ¶
DuplicateFeatureError builds the schema error for two feature fields that normalize to the same kebab-case name. The runtime schema builder and the static analyzer share it as the single source of truth.
func FailingFeatureTerms ¶ added in v0.9.0
FailingFeatureTerms lists the feature names whose state makes featureExpr false under activeFeatures: a plain term whose feature is off, and a negated term whose feature is on. It returns nil when the expression matches.
func FeatureEnvCollisionError ¶ added in v0.2.0
FeatureEnvCollisionError builds the schema error for one environment variable bound by two schema members: two feature fields resolving to the same variable, or a feature variable a flag also binds. The runtime schema builder and the static analyzer share it as the single source of truth.
func FeatureEnvModeConflictError ¶ added in v0.2.0
func FeatureEnvModeConflictError() error
FeatureEnvModeConflictError builds the schema error for a conga.Features container declaring both env and envprefix tags: env names the combined map variable while envprefix derives per-feature variables, and the two surfaces would compete over the same keys. The runtime schema builder and the static analyzer share it as the single source of truth.
func FeatureFieldDeclaresEnv ¶ added in v0.2.0
FeatureFieldDeclaresEnv reports whether a feature field's env tag names at least one environment variable. A missing tag, env:"-", and an empty tag are absence, so they never conflict with a combined-map container.
func FeatureFieldEnvWithContainerEnvError ¶ added in v0.2.0
FeatureFieldEnvWithContainerEnvError builds the schema error for a feature field declaring env while the Features container names a combined map variable: the two surfaces would write the same keys with no defined precedence between them. The runtime schema builder and the static analyzer share it as the single source of truth.
func FeatureFieldName ¶
FeatureFieldName derives the canonical kebab-case feature name of an inner feature struct field: the name tag when present, else the Go field name. The runtime schema builder and the static analyzer share it as the single source of truth for duplicate and empty-name diagnostics.
func FeatureFieldTypeError ¶
FeatureFieldTypeError builds the schema error for a feature field whose type is neither a bool nor an integer. The runtime schema builder reports it from the reflected field kind and the static analyzer reports it from the go/types kind, so the message stays a single source of truth.
func FeatureOnRequiredFlagError ¶
func FeatureOnRequiredFlagError() error
FeatureOnRequiredFlagError builds the schema error for a feature tag on a required flag: a feature-gated flag must be optional. The runtime schema builder and the static analyzer share it as the single source of truth.
func FeatureStageAllOrNothingError ¶
FeatureStageAllOrNothingError builds the schema error for a feature field that omits the stage tag while a sibling declares one. The runtime schema builder and the static analyzer share it as the single source of truth.
func FeatureTagRequiresEnableError ¶
func FeatureTagRequiresEnableError() error
FeatureTagRequiresEnableError returns the schema error for a feature:"..." struct tag declared under an app that never calls app.EnableFeatures(). The runtime schema builder and the static analyzer share it as the single source of truth.
func FeaturesAlreadyDeclaredError ¶
FeaturesAlreadyDeclaredError builds the duplicate-container error for a second conga.Features field on the root command struct. The runtime schema builder and the static analyzer share it as the single source of truth; firstFlagName is the resolved synthesized flag name of the first container.
func FeaturesMustBeOnRootError ¶
func FeaturesMustBeOnRootError() error
FeaturesMustBeOnRootError builds the schema error for a conga.Features container declared on a non-root command struct. The runtime schema builder returns it and the static analyzer reports it verbatim, keeping the message a single source of truth.
func FeaturesMustBeStructParameterError ¶
func FeaturesMustBeStructParameterError() error
FeaturesMustBeStructParameterError builds the schema error for a conga.Features container whose type parameter is not a struct. The runtime schema builder and the static analyzer share it as the single source of truth.
func FeaturesRequiresEnableError ¶
func FeaturesRequiresEnableError() error
FeaturesRequiresEnableError returns the schema error for a conga.Features container declared under an app that never calls app.EnableFeatures(). The runtime schema builder and the static analyzer share it as the single source of truth.
func FieldTagKeys ¶
FieldTagKeys returns the tag keys of tagSpecs for tag-candidate merging.
func FlagTokenResolves ¶ added in v0.6.0
FlagTokenResolves reports whether every flag a flag token names resolves on chain, built-ins visible on chain included. A long flag honors the no- negation form; a shorthand cluster resolves when WalkShorthand visits no unresolved rune, so runes consumed as a value are never resolved.
func FloatBoundParser ¶ added in v0.9.0
FloatBoundParser returns the range-bound parser for a float of bitSize bits (32 or 64). A float32 bound parses at float32 precision and widens to float64 the same way a float32 value does, so a value equal to its bound compares equal; a bound outside the float32 range fails to parse. Schema build, the binder, and conga-lint share it.
func GroupTagOnRequiredFlagError ¶ added in v0.4.0
GroupTagOnRequiredFlagError builds the schema error for an xor or oneof group tag declared on a required flag. Required flags are individually mandatory, so group tags belong on optional flags; oneof is the tag that expresses exactly-one semantics. The runtime schema builder and the static analyzer share it as the single source of truth.
func ImplicitCommandAlreadyDeclaredError ¶ added in v0.6.0
ImplicitCommandAlreadyDeclaredError builds the duplicate-command error for a second implicit command on one command struct. The runtime schema builder and the static analyzer share it as the single source of truth.
func ImplicitFlagDepth ¶ added in v0.6.0
ImplicitFlagDepth returns the number of implicit descendant levels required to resolve the flag tokens in tokens. The chain's leaf is the current command. It is the completion walker's entry point; the binder's terminal implicit selection computes the same depth through flagDepthInLevels inside TerminalImplicitLevels. Both surfaces therefore share one scan and cannot drift: flags already declared by the routed chain, built-ins, and flags declared nowhere contribute nothing, and tokens after the -- terminator are operands that never select a command.
func IsBuiltinFlag ¶ added in v0.6.0
IsBuiltinFlag reports whether flagSpec is one of the engine-synthesized built-in flags.
func IsBuiltinShortFlag ¶ added in v0.6.0
IsBuiltinShortFlag reports whether flagSpec is a built-in flag that can be selected by a shorthand (help or version).
func IsReservedPredictorName ¶
IsReservedPredictorName reports whether name is a reserved built-in predictor name or alias.
func MatchFeature ¶
MatchFeature reports whether featureExpr is satisfied by activeFeatures. featureExpr is a comma-separated conjunction of bare feature names, each optionally negated with a leading "!"; a feature is on when activeFeatures marks it true. The expression is parsed on every call, so schema build stores the NormalizeFeatureExpression form on flags and commands (no AST cache is kept); direct callers may pass a raw expression unchanged.
func NormalizeFeatureExpression ¶
NormalizeFeatureExpression canonicalizes an already-valid feature expression to its stored form: comma-separated terms with surrounding whitespace trimmed and empty terms dropped. Schema build validates the raw expression first and stores the normalized result on flags and commands, so display sites (help, --why, error messages) show one canonical spelling. Direct callers of MatchFeature are unaffected: it still accepts a raw expression.
func OneOfAndOverlapError ¶ added in v0.4.0
OneOfAndOverlapError builds the schema error for two members of the same oneof group that also share an and group: selecting either member forces the other, so the exactly-one rule can never be satisfied. The runtime schema builder and the static analyzer share it as the single source of truth.
func ParseFeatureContainerEnv ¶ added in v0.2.0
ParseFeatureContainerEnv resolves the combined map variable's environment names from the container tag: explicit env names only, with env:"-" and tag-less containers excluded from the environment tier entirely. Features never derive environment variables from any prefix. The runtime schema builder and the static analyzer share it as the single source of truth.
func ParseFeatureTag ¶
ParseFeatureTag parses, validates, and normalizes the "feature" struct tag expression.
func ParseFlagShort ¶ added in v0.4.0
ParseFlagShort returns the rune declared by a flag's short tag, or 0 when the tag is absent. It is the shared decoding rule for the runtime schema builder and the static analyzer, so both see the same rune when deciding whether a user-declared short collides with a built-in one.
func ParseGlobPatterns ¶
ParseGlobPatterns splits a comma-separated glob tag value into trimmed patterns and validates each one: empty elements, path separators, and malformed filepath.Match syntax are rejected at schema build. Patterns match file names (not paths) during completion traversal, so a wildcard-free pattern such as "Makefile" matches that literal name. Errors wrap ErrInvalidStructTag.
func ParseStrictBoolTag ¶
ParseStrictBoolTag parses a strict boolean struct tag: absence is reported via the present flag (value false), "" (bare presence) and "true" map to true, "false" maps to false, and any other value is a schema error. Security-adjacent tags must not fail silently, so a typo (e.g. safe:"ture") surfaces at schema build instead of silently inverting the tag's intent.
func ParseStrictStringTag ¶
ParseStrictStringTag parses a raw string struct tag for tagSpec: absence is reported via the present flag, an empty (all-whitespace) value is a schema error, and the spec's optional Validate hook checks the raw value. A hook error that already wraps ErrSchema propagates unchanged; any other hook error is wrapped with ErrInvalidStructTag and the tag name.
func ParseSummaryTag ¶
ParseSummaryTag validates and returns the summary tag, falling back to defaultSummary when the tag is absent.
func ProcessFeaturesField ¶
func ProcessFeaturesField(builder any, structField reflect.StructField, fieldHandle any, classification container.Classification) error
ProcessFeaturesField adapts processFeaturesField for the spec.Options hook.
func ProjectTextValue ¶
ProjectTextValue projects a coerced value of elemType into the caller's native domain. ok is false when elemType is not a text-range type, its domain does not match T, or the value cannot be projected.
func ResolveFlagEnvVars ¶ added in v0.2.0
ResolveFlagEnvVars resolves a flag field's environment variable names the way the schema builder does: an explicit env tag names the variables, env:"-" excludes them, and an untagged field derives one variable from envPrefix (<PREFIX>_<UPPER_SNAKE(flag name)>, with the trailing underscore normalized). The second result reports the exclusion. The static analyzer shares it as the single source of truth for derived variable names.
func RoutingFlagConsumesNext ¶ added in v0.6.0
RoutingFlagConsumesNext reports whether the token parser takes the token after tok as tok's value, resolved the way subcommand routing sees the invocation before an implicit command is entered: CLI flags declared on chain first, then the built-ins visible on chain, then CLI flags declared by the implicit descendants of chain's leaf, nearest first. It shares flagTokenDepth with TerminalImplicitLevels, so routing lookahead and terminal implicit selection agree on every token's arity; a value-taking implicit flag never shadows a built-in visible on chain.
func RoutingLeadingShortRegistered ¶ added in v0.6.0
RoutingLeadingShortRegistered reports whether the first shorthand of tok resolves on chain, as a built-in visible on chain, or on an implicit descendant of chain's leaf. The token parser classifies a negative number as a flag cluster when its first rune is registered, regardless of later runes.
func SingleMemberGroupError ¶ added in v0.5.0
SingleMemberGroupError builds the schema error for a group with only one member. A one-member xor or and group is a no-op; a one-member oneof group on an optional flag duplicates RequiredFlag. A one-member oneof on a Counter is legal and never reaches this constructor. The runtime schema builder and the static analyzer share it as the single source of truth.
func SplitTagList ¶
SplitTagList splits a comma-separated struct tag value into trimmed entries.
func TagCandidatesForRole ¶
TagCandidatesForRole returns the allowed struct tag key candidates for a schema field role. The second result reports whether the role is known.
func TerminalImplicitLevels ¶ added in v0.6.0
func TerminalImplicitLevels(chain []*Command, tokens []tokenizer.Token, terminatorOperands bool) int
TerminalImplicitLevels returns the number of implicit descendant levels the terminal route enters. The chain's leaf is the current command. A runnable command runs itself unless a flag declared only by its implicit descendants selects a deeper level; a command that does not own the operands after the -- terminator forwards them to its implicit child. A built-in rendering request counts only on the command where the built-in is visible, so a root-only --version never keeps a selected implicit child active. Callers perform the entry side effects for the returned levels.
func TextRangeParser ¶
TextRangeParser returns the bound parser for elemType in the caller's native domain. ok is false when elemType is not a text-range type or its domain does not match T.
func TrailingCollectorAlreadyDeclaredError ¶ added in v0.6.0
TrailingCollectorAlreadyDeclaredError builds the duplicate-container error for a second trailing-argument collector of one kind on a command struct. The runtime schema builder and the static analyzer share it as the single source of truth; containerName is "RawArgs" or "DashArgs" and firstFieldName is the struct field of the first declaration.
func ValidateBranchGrammar ¶ added in v0.6.0
func ValidateBranchGrammar(grammar BranchGrammar) error
ValidateBranchGrammar enforces the branch/leaf invariant: a command is either a branch (user subcommands) or a leaf (positional arguments), never both. Mixing the two lets a positional typed before a subcommand bind the routed leaf's arguments, which shifts positional indexes and the RawArgs boundary away from what the schema declares. Kong refuses the same shape as "can't mix positional arguments and branching arguments".
func ValidateConfigFileConfigTag ¶
ValidateConfigFileConfigTag rejects a config struct tag on a config file flag whose value is not "-".
func ValidateCountRangeSpec ¶
ValidateCountRangeSpec validates len/items range bounds as non-negative integers.
func ValidateCounterDefaultTag ¶
ValidateCounterDefaultTag rejects a default struct tag on a counter flag.
func ValidateFeatureEnvSurfaces ¶ added in v0.2.0
ValidateFeatureEnvSurfaces rejects ambiguous env declarations on the feature container: env and envprefix name different env surfaces (the combined map variable versus per-feature variables), and a field env tag under a combined-map container would create a second env surface writing the same keys. An env tag whose value is "-" or carries no names is absence, so it never conflicts. The runtime schema builder and the static analyzer share it as the single source of truth.
func ValidateFeatureExpression ¶
ValidateFeatureExpression validates that featureExpr conforms to valid feature tag syntax.
func ValidateFeatureFieldTags ¶
func ValidateFeatureFieldTags(field *FeatureField, tag reflect.StructTag) error
ValidateFeatureFieldTags validates and records the enum, default, and stage tags of one feature field: enum is valid only on integer features and may not be empty, every enum value must canonicalize within the feature's domain and storage width, an integer feature requires at least one enum level, a declared default must canonicalize against the enum domain, and a declared stage must name one of the four maturity levels. The runtime schema builder reports it from the reflected field and the static analyzer reconstructs the same metadata from go/types, keeping the diagnostics a single source of truth.
func ValidateFeatureReferences ¶
ValidateFeatureReferences rejects feature expressions that reference a feature not declared through the root conga.Features container.
func ValidateFieldTags ¶
func ValidateFieldTags(tag reflect.StructTag, role string, candidates []string, opts ValidationOptions) error
ValidateFieldTags validates the struct tags of a single schema field: tag syntax, disallowed tags, {{...}} help-variable references for the flag, positional-argument, and config-file-flag roles, and tag-key candidate membership for the field's role.
func ValidateImplicitFeature ¶ added in v0.9.0
ValidateImplicitFeature rejects a feature tag on an implicit command. An implicit command is entered without being named, so a gate on it would make the parent's operand and flag grammar depend on a feature. Gating the parent, or a flag of the implicit command, stays legal. The runtime schema builder and the static analyzer share it as the single source of truth.
func ValidateNonContainerFieldTags ¶ added in v0.5.0
func ValidateNonContainerFieldTags(tag reflect.StructTag, fieldTagKeys []string, opts ValidationOptions) error
ValidateNonContainerFieldTags rejects CONGA tags on fields that schema building ignores. Plain struct fields are not flattened, so a tag such as name or help on one would silently do nothing; surfacing it as a schema error keeps the declaration honest. fieldTagKeys carries the domain-type tags the field's value type registers, which are equally ignored on a plain field. Tag syntax is always validated; well-formed foreign keys are ignored, and keys listed in AllowedTags are accepted. The reserved ~-prefixed namespace and the required tag stay rejected regardless of AllowedTags, mirroring container roles. The static analyzer resolves only the built-in CONGA domain types, so user-defined TagSpecProviders stay runtime-only, and it skips the key rejection when it cannot prove the allow-list (SkipUnknownTagKeyCheck), so it never invents a diagnostic. Unexported fields never reach this check, so embedded behavior mixins remain supported.
func ValidatePredictorTag ¶
func ValidatePredictorTag(tag reflect.StructTag, isBool bool, registeredNames []string, checkCustomNames bool) error
ValidatePredictorTag validates an explicit predictor:"..." struct tag without runtime predictor inference: built-in predictor vocabulary is always checked; custom predictor names must be registered unless checkCustomNames is false. The static analyzer passes false when app.Predictor evidence is ambiguous, so it may only miss diagnostics, never invent them; the runtime schema builder always checks custom names.
func ValidateScalarRange ¶
func ValidateScalarRange[T cmp.Ordered](rangeSpec *Range, boundKind string, parse func(string) (T, error)) error
ValidateScalarRange parses the min/max bounds of rangeSpec with parse and checks their order. boundKind names the value kind in parse-error messages ("duration", "integer", "unsigned integer", "float", "byte size", "value").
func ValidateTextBounds ¶ added in v0.9.0
ValidateTextBounds checks each declared bound side with validate, which rejects a bound the field's tags don't accept (a decimal byte size under units:"binary"). The message keeps validate's reason. Schema build and the static analyzer share it, so both report the same diagnostic.
func ValidateTrailingGrammar ¶ added in v0.6.0
func ValidateTrailingGrammar(grammar TrailingGrammar) error
ValidateTrailingGrammar enforces a deterministic RawArgs boundary: a command declaring RawArgs may not also declare any command field, and every positional argument before the collector must be a required scalar. RawArgs is a leaf collector; DashArgs remains the explicit '--'-delimited alternative for commands that also branch.
func VersionJSONShadowError ¶ added in v0.9.0
VersionJSONShadowError builds the shadowing error for the built-in version command's --json selector, which the user cannot rename, with a migration hint. descendant names the VersionCommand field.
func XorAndOverlapError ¶ added in v0.5.0
XorAndOverlapError builds the schema error for two members of the same xor group that also share an and group: supplying either member forces the other, so the mutually-exclusive rule can never be satisfied. The runtime schema builder and the static analyzer share it as the single source of truth.
Types ¶
type Arg ¶
type Arg struct {
Name string
Default string
Help string
// HelpVars records the help-text variables the argument's help tag
// referenced; the renderer suppresses the matching automatic hint for each
// one.
HelpVars helpVars
// EnumHintHidden reports whether the enumhint struct tag opted the argument
// out of the automatic [enum: ...] help hint. Declared values stay
// validated and completed; only the help-screen listing is suppressed.
EnumHintHidden bool
Enum []string
Range *Range
Len *Range
Items *Range
// FieldTags holds the custom tag values declared on the argument that
// were registered by its domain type (see spec.TagSpecProvider). Nil
// when the argument's type registers no tags or declares none.
FieldTags FieldTags
Sep string
IsSlice bool
IsMap bool
Bootstrap bool
Required bool
Predictor *PredictorSpec
TargetType reflect.Type
// Handle is the engine's opaque handle to the argument's container value. It
// is never inspected by this package: package conga stores the field address
// here and re-asserts its private engine interfaces at bind time. Nil when
// the field was not classified.
Handle any
}
Arg represents the metadata and binder for a positional argument.
type BranchGrammar ¶ added in v0.6.0
type BranchGrammar struct {
// PositionalField is the first declared positional argument field.
PositionalField string
// SubcommandField is the first declared user subcommand field. Built-in
// help, version, and completion commands do not count as branching.
SubcommandField string
}
BranchGrammar describes whether one command declares positional arguments and user subcommands. It carries the field names so the branch/leaf invariant can report both sides of the conflict.
type Command ¶
type Command struct {
Name string
Aliases []string
Summary string
Description string
Examples string
Deprecated string
Section string
Hidden bool
EnvPrefix string
Version string
// CompletionEnvPrefix is the normalized (trailing-underscore) prefix of the
// application-prefixed completion sideband variables, for example TASK_.
// It is populated on the root command during schema build and read by
// completion script generation and the __complete runtime path.
CompletionEnvPrefix string
IsHelpCmd bool
IsVersionCmd bool
IsCompletionCmd bool
// IsCompletionFlag is true when a completion command was synthesized from the
// --completion flag on a flat CLI, tailoring help screens to flag syntax.
IsCompletionFlag bool
// Shell names the completion target shell for IsCompletionCmd commands,
// populated during binding so `completion <shell> --help` renders that
// shell's enable instructions. Empty on all other commands.
Shell string
// HelpShort and VersionShort carry the optional short runes assigned to the
// injected built-in --help and --version flags through app.HelpShortFlag and
// app.VersionShortFlag. They are populated on the root command during schema
// build and read by the binder (short-flag registration) and the help
// renderer (flag rows). Zero keeps the built-in long-only.
HelpShort rune
VersionShort rune
Flags []*Flag
Args []*Arg
Subcommands []*Command
// Implicit marks a subcommand that may be selected without naming it.
Implicit bool
// IsRunnable records whether the command target implements conga.Runner.
// The builder populates it from Options.IsRunner for user and declared
// built-in commands; routing and completion use it as the single authority
// for the terminal implicit-command rule. Specs built without
// Options.IsRunner report false, so callers building specs manually must set
// it when implicit routing matters.
IsRunnable bool
DashArgs *DashArgs
RawArgs *RawArgs
ConfigFileFlag *Flag
// ConfigSettings holds the app-level configuration resolution settings
// (app.ConfigOptions options) injected onto the root command during build.
// Empty on subcommands.
ConfigSettings ConfigSettings
Target any
// Handle is the engine's opaque handle to the subcommand's container value.
// It is never inspected by this package: package conga stores the field
// address here and re-asserts its private engine interfaces at bind time.
// Nil when the field was not classified.
Handle any
DisableCompletion bool
DisableHelp bool
DisableVersion bool
DisableWhy bool
// WhyJSONEnabled reports whether the app enabled the machine-readable
// JSON output format for the built-in --why flag via
// app.EnableWhy(conga.WhyOptionJSON()). The help renderer and completion engine
// use it to advertise the value slot only when more than the default text
// format is accepted.
WhyJSONEnabled bool
// Feature holds the feature-gate expression declared through the feature
// tag on a subcommand container field. Empty means the subcommand is not
// feature-gated.
Feature string
// FeatureFields lists the root feature declarations reflected from the
// conga.Features[T] container. Empty on subcommands.
FeatureFields []*FeatureField
// FeatureFlag is the synthesized map flag that carries feature values from
// the command line, environment, and configuration files. Nil when no
// Features container is declared; the flag is always installed for a
// declared container (NoCLI only removes CLI routing).
FeatureFlag *Flag
// contains filtered or unexported fields
}
Command represents the metadata and AST definition of a command node.
func NewCompletionCommand ¶
func NewCompletionCommand(name, summary string, target any, aliases []string, hidden bool, shells []string) *Command
NewCompletionCommand creates a completion subcommand definition for target. shells enumerates the supported shell names and is supplied by the caller: schema building must not reach the completion subsystem directly.
func (*Command) CompletionFlagVisible ¶
CompletionFlagVisible reports whether the built-in --completion flag is offered for this command: only on the root command of a flat CLI without a completion subcommand. It is the single authority used by the binder, help renderer, and completion engine so --completion handling stays consistent.
func (*Command) FeatureNames ¶
FeatureNames returns the normalized names of every declared feature.
func (*Command) FindFeature ¶
func (c *Command) FindFeature(name string) *FeatureField
FindFeature returns the declared feature matching name, or nil.
func (*Command) FindFlag ¶
FindFlag returns the flag matching name or alias, or nil. NoCLI engine flags are included; CLI-facing callers use findCLIFlagInChain instead.
func (*Command) FindShortFlag ¶
FindShortFlag returns the flag matching short rune r, or nil. NoCLI engine flags are included; CLI-facing callers use findCLIShortFlag instead.
func (*Command) FindSubcommand ¶
FindSubcommand returns the subcommand matching name or alias, or nil.
func (*Command) HasCompletionCommand ¶
HasCompletionCommand reports whether this command contains a completion subcommand.
func (*Command) HasUserSubcommands ¶
HasUserSubcommands returns true if this command has user-declared subcommands (excluding built-in help, version, and completion).
func (*Command) ImplicitCommand ¶ added in v0.6.0
ImplicitCommand returns the subcommand selected when no explicit subcommand claims the invocation, or nil. Schema build accepts at most one implicit command per command, so the first match is authoritative.
func (*Command) InheritBuiltinVisibilityFrom ¶ added in v0.2.0
InheritBuiltinVisibilityFrom copies the app-wide built-in flag visibility toggles (DisableHelp, DisableVersion, DisableWhy, WhyJSONEnabled, DisableCompletion) from src onto a synthesized builtin subcommand. The toggles are decided once on the root from the app builder state and are propagated to user-declared subcommands by the schema builder; synthesized commands (help, version, completion, and the ephemeral per-shell completion help screens) are not built through that path, so they inherit explicitly here. Leaf-level visibility checks (binder, help renderer, completion engine) then agree with the root schema options.
func (*Command) VersionFlagVisible ¶
VersionFlagVisible reports whether the built-in --version flag is offered for this command: version information describes the whole application, so the flag exists only on the root command unless explicitly disabled. It is the single authority used by the binder, help renderer, and completion engine so --version handling stays consistent.
func (*Command) WhyFlagVisible ¶
WhyFlagVisible reports whether the built-in --why flag is offered for this command: like --help, the flag is available on every command, and the provenance report it renders describes the whole invocation. It is the single authority used by the binder, help renderer, and completion engine so --why handling stays consistent.
func (*Command) WhyFormats ¶ added in v0.2.0
WhyFormats returns the output formats advertised for the built-in --why flag: the default text format alone, or text and json when the app enabled app.EnableWhy(conga.WhyOptionJSON()). Help and completion read this list so the advertised formats stay a single source of truth; parse-time value validation remains with the app's why resolver.
type CompleteOptions ¶
type CompleteOptions struct {
RegisteredPredictors map[string]predict.Predictor
Env map[string]string
EnvLookup func(string) (string, bool)
Dir string
}
CompleteOptions configures the execution of the completion engine.
Env and EnvLookup scope the environment view handed to predictors through predict.Context; EnvLookup is consulted first, then Env. They do not override the application-prefixed sideband toggles (aliases, descriptions, bare-space flags), which the framing layer reads from the process environment because they describe the invoking shell session.
type CompletionAnalysis ¶
type CompletionAnalysis struct {
CommandChain []*Command
FlagValues map[*Flag][]string
PositionalArgs []string
DashArgs []string
RawArgs []string
}
CompletionAnalysis carries the invocation facts parsed from the typed portion of a completion command line. It is produced before feature pruning so the engine can resolve configuration and bind bootstrap fields from the same tokens the candidate pass will later see.
func AnalyzeCompletion ¶
func AnalyzeCompletion(rootCmd *Command, args []string) CompletionAnalysis
AnalyzeCompletion parses every complete word in args (all words except the fragment being completed) with the same tolerant walker used for candidate generation. It performs no candidate resolution and does not mutate the command tree. Command routing runs first so raw fallback is evaluated against the routed leaf, matching the runtime parser.
type ConfigSettings ¶
type ConfigSettings struct {
// Explicit names one concrete configuration file with fatal-if-missing
// semantics. It outranks the configuration environment variable and the
// search tier.
Explicit string
// Tier lists the author-declared search paths probed in precedence order.
// Declaring a tier replaces the built-in conventional XDG tier.
Tier []string
// Cascading merges every existing tier file in precedence order (lowest to
// highest) instead of stopping at the first existing file.
Cascading bool
// KeyCase spells the config keys derived from flag, subcommand, and
// feature names. Explicit config tags are used as written.
KeyCase KeyCase
}
ConfigSettings carries the app-level configuration-file resolution settings declared through the app.ConfigOptions(...) builder. They ride through schema build as this typed struct on the root command so resolution, validation, and static analysis share one source of truth. The "~"-prefixed struct tag namespace (~explicit, ~searchpaths, ~cascading) is a pure reservation: source-declared "~"-prefixed struct tags are rejected so the vocabulary stays engine-owned, and no diagnostic names these keys.
type DashArgs ¶
type DashArgs struct {
Name string
// Predictor declares the completion candidates for the captured tokens.
// The none predictor means no candidates (the collector is opaque); schema
// build stores it when the tag is absent, and a nil field behaves the same
// for hand-built specs. Only the explicit predictor struct tag applies;
// type inference never runs for a trailing collector.
Predictor *PredictorSpec
Bootstrap bool
// Handle is the engine's opaque handle to the '--' trailing-arguments
// container value. It is never inspected by this package and nil when not
// classified.
Handle any
}
DashArgs represents the binder for arguments explicitly passed after '--'.
type FeatureField ¶
type FeatureField struct {
// Name is the normalized kebab-case feature name (the map key).
Name string
// Help is the human-readable description shown in the root help screen's
// Features section and in completion candidate descriptions.
Help string
// Stage is the declared feature maturity: FeatureStageAlpha,
// FeatureStageBeta, FeatureStageGA, or FeatureStageDeprecated, or "" when
// the stage tag is absent on every feature field. GA and deprecated
// features are omitted from the help screen's Features section.
Stage string
// IsInt reports whether the feature is a leveled integer toggle (0 = off).
IsInt bool
// IsUnsigned reports whether the feature's integer field is an unsigned
// kind, so negative values are rejected at canonicalization.
IsUnsigned bool
// BitSize is the storage width of the feature's integer field in bits; zero
// for bool features.
BitSize int
// Enum lists the permitted non-zero values of an integer feature, in
// declaration order. Empty for bool features.
Enum []string
// Default is the canonical default value ("true"/"false" for bools, a decimal
// string for integers), or "" when no default tag is declared.
Default string
// EnvVars lists the environment variables the feature binds in declaration
// order: the env tag names when present, else the name derived from the
// container's envprefix tag. Empty when the field binds no environment
// variable.
EnvVars []string
// EnvExcluded reports that the feature binds no environment variable,
// whether through an env:"-" tag or the absence of both an env tag and a
// container envprefix.
EnvExcluded bool
// FieldIndex is the index of the feature field inside the inner feature struct.
FieldIndex int
}
FeatureField describes one field of the root conga.Features[T] struct: a single feature toggle.
func (*FeatureField) Canonicalize ¶
func (f *FeatureField) Canonicalize(raw string) (string, error)
Canonicalize coerces a raw feature value to its canonical form: "true" or "false" for bool features, and a decimal string for integer features. It rejects values outside the feature's declared domain, negative values of unsigned fields, and values that do not fit the field's storage width.
func (*FeatureField) Domain ¶
func (f *FeatureField) Domain() []string
Domain returns the canonical value domain for the feature toggle: "0" followed by the enum values for an integer feature, or "true" and "false" for a boolean feature.
func (*FeatureField) ListedInHelp ¶
func (f *FeatureField) ListedInHelp() bool
ListedInHelp reports whether the feature toggle is rendered in the root help screen's Features section: undeclared, alpha, and beta stages are listed, while GA and deprecated features — no longer experimental — are omitted.
type FieldTags ¶
FieldTags holds the custom tag values declared on the field owning a resolved value. Only tags registered by the field's domain type appear; boolean values are canonicalized to "true" and "false", string values are stored verbatim.
func ParseFieldTags ¶
ParseFieldTags extracts the declared custom field tag values for tagSpecs: each registered key present in the struct tag is parsed per its kind, and excluded combinations are rejected as schema errors. Tags not registered by the domain type are ignored here; strict tag-key validation governs whether they are permitted at all.
type Flag ¶
type Flag struct {
Name string
// StructName and FieldName name the Go struct and field that declare the
// flag, so diagnostics can point at the declaration. For the built-in
// version command's --json they name the VersionCommand field.
StructName string
FieldName string
Short rune
Aliases []string
Default string
EnvVars []string
EnvExcluded bool
ConfigKey string
// XorGroup names an optional mutually-exclusive group: at most one member
// may be supplied. Declared through xor:"group"; rejected on required flags.
XorGroup string
// AndGroup names a co-occurrence group: members must be supplied together.
AndGroup string
// OneOfGroup names an exactly-one group: exactly one member must be
// supplied. Declared through oneof:"group"; rejected on required flags.
OneOfGroup string
Enum []string
Range *Range
Len *Range
Items *Range
// FieldTags holds the custom tag values declared on the flag that were
// registered by its domain type (see spec.TagSpecProvider). Nil when the
// flag's type registers no tags or declares none.
FieldTags FieldTags
Help string
// HelpVars records the help-text variables the flag's help tag referenced;
// the renderer suppresses the matching automatic hint for each one.
HelpVars helpVars
// EnumHintHidden reports whether the enumhint struct tag opted the flag out
// of the automatic [enum: ...] help hint. Declared values stay validated
// and completed; only the help-screen listing is suppressed.
EnumHintHidden bool
Placeholder string
Section string
Hidden bool
// Safe reports whether the resolved value may be displayed in the --why
// provenance report. Declared via the safe struct tag; an absent tag
// defaults to true for boolean and counter flags (their value domain can
// never carry credential material) and false for every other flag type.
Safe bool
Deprecated string
Sep string
IsBool bool
IsSlice bool
IsMap bool
IsCounter bool
IsNegatable bool
IsConfigFile bool
// EngineOwned marks flags synthesized by the engine rather than declared
// by user struct fields. The engine binds them by identity and they never
// resolve into user containers. Engine-owned flags take part in ancestor
// flag shadowing like declared flags; a NoCLI flag is the exception
// because it never appears on the command line.
EngineOwned bool
// NoCLI marks an engine-synthesized flag that binds environment and
// configuration values but is excluded from command-line routing and help.
NoCLI bool
// Bootstrap reports whether the field is bound in the bootstrap pass,
// before configuration resolution, and exposed to the Bootstrapper typed.
Bootstrap bool
// Required reports whether the flag was declared through a required
// container (conga.RequiredFlag[T]).
Required bool
// Handle is the engine's opaque handle to the flag's container value. It is
// never inspected by this package: package conga stores the field address
// here and re-asserts its private engine interfaces at bind time. Nil when
// the field was not classified.
Handle any
Predictor *PredictorSpec
TargetType reflect.Type
// KeyCanonicalizer optionally canonicalizes keys during map tier merging.
KeyCanonicalizer func(string) string
// Feature holds the feature-gate expression declared through the feature
// tag on the flag's owning field. Empty means the flag is not
// feature-gated.
Feature string
}
Flag represents the metadata and binder for a command-line flag.
func FindFlagInChain ¶
FindFlagInChain searches backwards through chain for a CLI-routable flag matching name or alias, falling back to the built-in --help, --version, --completion, and --why flags. NoCLI engine flags are excluded.
func FindShortFlagInChain ¶
FindShortFlagInChain searches backwards through chain for a CLI-routable flag matching short rune r, falling back to the built-in --help and --version flags when r is the rune assigned to them through app.HelpShortFlag/app.VersionShortFlag and no declared CLI flag shadows the corresponding built-in long name. NoCLI engine flags are excluded.
func ResolveNegatedFlag ¶ added in v0.6.0
ResolveNegatedFlag resolves the positive flag behind a `no-`-prefixed long flag name through lookup, enforcing the CanNegate guard: a no- token may only re-bind a boolean negatable flag.
func (*Flag) TakesValue ¶ added in v0.6.0
TakesValue reports whether the flag consumes a value from the command line. Boolean and counter flags are toggles and do not take a value.
type FlagOwner ¶ added in v0.9.0
FlagOwner names the declaration of a flag name, alias, or short rune for shadowing diagnostics: the command that declares it and the Go struct and field that hold it.
type GroupCensus ¶ added in v0.5.0
type GroupCensus[T any] struct { // contains filtered or unexported fields }
GroupCensus counts the members of every flag group declared on one command. Group validation is command-scoped, so each command build owns one census. Declaration order is preserved so the first offending group is reported deterministically. The runtime schema builder and the static analyzer share this type as the single source of truth for the single-member policy.
func NewGroupCensus ¶ added in v0.5.0
func NewGroupCensus[T any]() *GroupCensus[T]
NewGroupCensus returns an empty census.
func (*GroupCensus[T]) Add ¶ added in v0.5.0
func (c *GroupCensus[T]) Add(kind, group, flagName string, isCounter bool, attribution T)
Add records one declared membership; an empty group name is ignored.
func (*GroupCensus[T]) SingleMemberGroups ¶ added in v0.5.0
func (c *GroupCensus[T]) SingleMemberGroups() []SingleMemberGroup[T]
SingleMemberGroups returns every group that fails the arity policy, in first-declaration order. A one-member oneof on a Counter stays legal: it is the tag-declarative way to require at least one occurrence; a one-member oneof on an optional flag duplicates RequiredFlag, and one-member xor/and groups are always no-ops.
type KeyCase ¶ added in v0.9.0
type KeyCase uint8
KeyCase selects how config keys derived from flag, subcommand, and feature names are spelled. Every derived key has exactly one spelling; explicit config tags are always used as written.
type Options ¶
type Options struct {
AllowedTags []string
RegisteredPredictors map[string]predict.Predictor
TypePredictors map[reflect.Type]predict.Predictor
ConfigFilePatterns []string
// ConfigDecoders lists the raw registered configuration decoder
// extensions (e.g. ".json", ".hcl") driving the positive decoder
// annotation on the config-file flag's help text.
ConfigDecoders []string
// ClassifyContainer maps a command-struct field address to its engine
// classification (container kind, required flag, command target). Nil
// leaves every field unclassified, so no field is treated as a container.
ClassifyContainer func(any) container.Classification
// IsBootstrapper reports whether a command struct implements the
// conga.Bootstrapper lifecycle interface. The builder calls it for every
// command during schema build and records the result in HasBootstrapper so
// a bootstrap-tagged field is only accepted under a command (or ancestor)
// that consumes it.
IsBootstrapper func(any) bool
// ReadsWhileParsing reports whether coercing a value of a type does
// irreversible I/O (conga.FileContent reads its file). Bootstrap fields
// are coerced twice, so schema build rejects such types, and slices or
// maps of them, on bootstrap fields. Nil disables the check.
ReadsWhileParsing func(reflect.Type) bool
// HasBootstrapper reports whether this command or one of its ancestors
// implements conga.Bootstrapper. It is derived from IsBootstrapper during
// the build walk and inherited by descendant commands.
HasBootstrapper bool
// IsRunner reports whether a command struct implements conga.Runner. The
// builder records the result in Command.IsRunnable so completion analysis
// can mirror the runtime terminal implicit-command rule. Hand-built specs
// that omit it report every command as non-runnable.
IsRunner func(any) bool
// ConfigSettings carries the app-level configuration resolution settings
// (app.ConfigOptions options) onto the root command.
ConfigSettings ConfigSettings
ConfigCapable bool
DisableHelp bool
DisableVersion bool
// HelpShort and VersionShort assign optional short runes to the injected
// built-in --help and --version flags (app.HelpShortFlag / app.VersionShortFlag).
// Zero keeps them long-only. A rune colliding with a user-declared short is
// rejected with ErrDuplicateFlag during schema build.
HelpShort rune
VersionShort rune
DisableWhy bool
// WhyJSONEnabled advertises the machine-readable JSON output format for
// the built-in --why flag. It only affects help and completion
// presentation; value validation stays with the app's why resolver.
WhyJSONEnabled bool
// DisableCompletion excludes every completion entry point from the schema:
// no `completion` subcommand is mounted and no `--completion` flag is
// offered. A command struct that declares a completion command field while
// completion is disabled is rejected with an ErrSchema naming the fix,
// rather than silently dropped.
DisableCompletion bool
// CompletionShells enumerates the shells the completion subsystem supports;
// it is supplied by the caller only when completion is enabled.
CompletionShells []string
// InferPredictor returns the predictor spec inferred from a field's Go type
// (Predictable, TagAwarePredictable, FileFilterable, DirFilterable,
// PathFilterable) when the field declares no explicit predictor tag. It is
// supplied by the caller only when completion is enabled; nil disables
// type-based inference, and inferred predictors are consumed exclusively by
// completion.
InferPredictor func(targetType reflect.Type, tags FieldTags) *PredictorSpec
// FeaturePredictor builds the predictor spec for the feature map flag's
// keys from the flag's resolved name, the declared feature value domains,
// and the per-feature help descriptions. It is supplied by the caller only
// when completion is enabled; nil omits key completion so the predictor
// package stays unreferenced.
FeaturePredictor func(name string, values map[string][]string, descriptions map[string]string) *PredictorSpec
// ValidateTextRangeBound checks a range bound against the owning field's
// declared custom tags before the default text grammar parses it. It is
// supplied by the caller (the root package) so tag-aware domain types can
// enforce constraints the plain UnmarshalText call cannot see; a nil hook
// leaves the default parser alone, and a nil return from the hook for
// unhandled types also falls through to the default parser.
ValidateTextRangeBound func(targetType reflect.Type, tags FieldTags, raw string) error
// ProcessFeatures processes a conga.Features container field during schema build.
ProcessFeatures func(builder any, structField reflect.StructField, fieldAddr any, classification container.Classification) error
// ValidateFeatureReferences validates feature expressions across commands and flags.
ValidateFeatureReferences func(root *Command) error
// ParseFeatureTag parses, validates, and normalizes a feature struct tag.
ParseFeatureTag func(raw string, required bool) (string, error)
EnvPrefix string
}
Options configure schema reflection, validation, and predictors.
type PredictorKind ¶
type PredictorKind int
PredictorKind identifies the type of completion predictor.
const ( // PredictorKindCustom indicates a user-registered dynamic predictor. PredictorKindCustom PredictorKind = iota // PredictorKindFile indicates built-in file completion (with optional extension filters). PredictorKindFile // PredictorKindDir indicates built-in directory completion. PredictorKindDir // PredictorKindExec indicates built-in PATH executable completion. PredictorKindExec // PredictorKindSymlink indicates built-in symlink completion. PredictorKindSymlink // PredictorKindNone indicates completion should be suppressed (no file fallback). PredictorKindNone // PredictorKindPredictable indicates a direct predict.Predictor (e.g. from Predictable interface). PredictorKindPredictable )
type PredictorSpec ¶
type PredictorSpec struct {
Kind PredictorKind
Name string
Patterns []string
Predictor predict.Predictor
}
PredictorSpec represents the parsed predictor configuration on a flag, positional argument, or trailing-argument collector.
func InferPredictorFromType ¶
func InferPredictorFromType(targetType reflect.Type, tags FieldTags) *PredictorSpec
InferPredictorFromType returns the predictor spec inferred from a domain type implementing Predictable, TagAwarePredictable, FileFilterable, DirFilterable, or PathFilterable. It is assigned to Options.InferPredictor by callers that enable the completion subsystem; referencing it from an always-linked path would keep the inference machinery (including its filesystem probes) in every binary.
type Range ¶
Range represents parsed range bounds for numeric, length, or collection constraints.
func ParseRangeSpec ¶
ParseRangeSpec parses a range tag value (min..max, min.., ..max, or exact).
type RangeDomain ¶
type RangeDomain uint8
RangeDomain selects the native comparison domain of a text-grammar range type. Bytes() int64 projections and signed integer kinds compare as int64, unsigned integer kinds as uint64, and float kinds as float64.
const ( // RangeSigned compares bounds and values as int64: Bytes() int64 // projections and signed integer underlying kinds. RangeSigned RangeDomain = iota // RangeUnsigned compares bounds and values as uint64: unsigned integer // underlying kinds. RangeUnsigned // RangeFloat compares bounds and values as float64: float underlying // kinds. RangeFloat )
func TextRangeDomain ¶
func TextRangeDomain(elemType reflect.Type) (RangeDomain, string, bool)
TextRangeDomain reports whether elemType carries range bounds through its own encoding.TextUnmarshaler grammar, and which native domain compares it. Bound parsing reads every bound into a fresh instance via UnmarshalText, so the type's own grammar is the single source of truth; boundKind names the kind in parse-error messages ("byte size" for Bytes() int64 projections, "value" for numeric-underlying dialects). Pointer element types and types without an ordered projection are rejected.
type RawArgs ¶
type RawArgs struct {
Name string
// Predictor declares the completion candidates for the captured tokens
// once raw mode begins. The none predictor means no candidates (the
// collector is opaque); schema build stores it when the tag is absent, and
// a nil field behaves the same for hand-built specs. Only the explicit
// predictor struct tag applies; type inference never runs for a trailing
// collector.
Predictor *PredictorSpec
Bootstrap bool
// Handle is the engine's opaque handle to the raw trailing-tokens
// container value. It is never inspected by this package and nil when not
// classified.
Handle any
}
RawArgs represents the binder for unparsed trailing raw arguments.
type ShorthandStep ¶ added in v0.6.0
type ShorthandStep struct {
// Flag is the flag the rune resolves to.
Flag *Flag
// ImplicitLevel is the implicit level that first declares Flag: 0 for the
// routed chain or a built-in.
ImplicitLevel int
// ValueStart reports that this rune takes the cluster remainder, the
// attached value, or the next token as its value. It is always the last
// step.
ValueStart bool
}
ShorthandStep records one resolved rune of a shorthand cluster. Its index in ShorthandWalk.Steps is the index of the rune it resolves.
type ShorthandWalk ¶ added in v0.6.0
type ShorthandWalk struct {
// Steps holds one entry per resolved rune, in rune order, up to and
// including the first value-taking rune.
Steps []ShorthandStep
// ConsumesNext reports whether the cluster takes the following token as a
// value: its final rune takes a value and no value is attached.
ConsumesNext bool
// UnresolvedAt is the index of the first rune that resolved to no flag, or
// -1 when every visited rune resolved.
UnresolvedAt int
}
ShorthandWalk is the arity classification of one shorthand cluster. It is the single source of the cluster arity rules shared by the token parser, routing lookahead, implicit-depth scanning, and the completion walker.
func WalkShorthand ¶ added in v0.6.0
func WalkShorthand(runes []rune, hasAttachedValue bool, resolve func(rune) (*Flag, int)) ShorthandWalk
WalkShorthand resolves runes in order, stopping at the first value-taking or unresolved rune. resolve returns the flag and the implicit level that first declares it (0 for the routed chain or a built-in), or a nil flag when the rune is not registered. hasAttachedValue mirrors the parser's arity rule: a final value-taking rune consumes the next token only when no value is attached. Runes after a value-taking rune are part of its value and are never resolved. The walker classifies only; callers bind values themselves.
type SingleMemberGroup ¶ added in v0.5.0
type SingleMemberGroup[T any] struct { Kind string Group string FlagName string Suggestion string Attribution T }
SingleMemberGroup records one declared group that fails the arity policy. Attribution carries caller metadata: the runtime stores the struct field name, the analyzer stores the declaring field object.
type TagKind ¶
type TagKind int
TagKind describes how a custom field tag's value is parsed and validated.
const ( // TagKindBool declares a strict boolean tag value: absence means false, // while "", "true", and "false" are the only accepted values. Typos fail // at schema build instead of silently inverting the tag's intent. TagKindBool TagKind = iota // TagKindString declares a raw string tag value: absence leaves the tag // undeclared, an empty (all-whitespace) value fails at schema build, and // the spec's optional Validate hook (see TagSpec) validates the raw // value at schema build. TagKindString )
type TagSpec ¶
type TagSpec struct {
// Name is the struct tag key (e.g. "existing").
Name string
// Kind selects the value grammar parsed at schema build.
Kind TagKind
// Validate optionally checks the raw string value of a TagKindString
// tag at schema build (both at runtime and in the static analyzer,
// which shares this parse path). The returned error should be
// self-describing; ParseFieldTags wraps it with ErrInvalidStructTag
// unless it already wraps ErrSchema, in which case it is propagated
// unchanged.
Validate func(value string) error
// Excludes lists tag keys that cannot be declared together with this
// tag; declaring both is a schema error.
Excludes []string
}
TagSpec declares a single custom struct tag accepted by a domain type. Domain types register their specs via TagSpecProvider; the specs feed the strict tag-key vocabulary, schema-time value parsing, and combination exclusion checks for the fields that use the type.
func ConfigFileFieldTagSpecs ¶
func ConfigFileFieldTagSpecs() []TagSpec
ConfigFileFieldTagSpecs returns the tag specs of the config-file flag role that the engine owns: multi switches the flag to multi-value arity (repeated --config-file, sep-split values). Flag arity is an engine concern, so the specs are engine-owned and shared by the config-file container adapters.
type TagSpecProvider ¶
type TagSpecProvider interface {
TagSpecs() []TagSpec
}
TagSpecProvider is implemented by domain types that accept custom struct tags on the fields that use them. Schema build consults the zero value and a pointer to the field's element type, so specs may be exposed through value or pointer receivers.
type TrailingArgGrammar ¶ added in v0.6.0
type TrailingArgGrammar struct {
// Name is the display name used in diagnostics.
Name string
// Required reports whether the argument must be supplied.
Required bool
// IsSlice reports whether the argument collects repeated values.
IsSlice bool
// IsMap reports whether the argument collects key/value entries.
IsMap bool
}
TrailingArgGrammar describes one positional argument preceding a RawArgs collector.
type TrailingGrammar ¶ added in v0.6.0
type TrailingGrammar struct {
// HasRawArgs reports whether the command declares a RawArgs collector.
HasRawArgs bool
// CommandField is the first declared command field, including built-in
// help, version, and completion command fields. It names the conflicting
// field in the RawArgs diagnostic and is empty when none is declared.
CommandField string
// Args lists every declared positional argument in declaration order.
Args []TrailingArgGrammar
}
TrailingGrammar describes the trailing-argument grammar of one command for the RawArgs boundary invariant. It carries only classification metadata so schema build and the static analyzer share one validation source.
type ValidationOptions ¶
type ValidationOptions struct {
// AllowedTags lists additional struct tag keys accepted by tag
// validation (app.AllowTags equivalent).
AllowedTags []string
// SkipUnknownTagKeyCheck suppresses unknown struct tag key checks. The
// static analyzer sets it when app.AllowTags evidence is ambiguous, so it
// may only miss diagnostics, never invent them; the runtime schema builder
// never sets it.
SkipUnknownTagKeyCheck bool
// EnvPrefix is the effective environment variable prefix of the command
// declaring the field, used to decide whether {{env}} is available in a help
// tag. It is only consulted when EnvPrefixKnown is true.
EnvPrefix string
// EnvPrefixKnown reports whether EnvPrefix was resolved. An unresolved
// prefix leaves {{env}} available, so evidence the analyzer cannot see never
// produces a diagnostic the runtime would not report.
EnvPrefixKnown bool
}
ValidationOptions carries the schema-build options that affect struct tag validation. A static analyzer reconstructs them from the app builder chain (app.AllowTags) instead of runtime reflection.