Documentation
¶
Overview ¶
Package spec builds and validates command schemas from application structs.
Index ¶
- Constants
- Variables
- func BootstrapFeatureConflictError() error
- func BootstrapFieldTypeError() error
- func BootstrapRequiresLoaderError() error
- func BootstrapTagged(tag reflect.StructTag) bool
- 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 ConfigLoaderConfigFileConflictError(flagName string) error
- func ConfigLoaderDecoderConflictError() error
- func ConfigLoaderOptionsConflictError() error
- func DefaultTypeHelp(targetType reflect.Type, tags FieldTags) string
- func DuplicateFeatureError(name string, typeName string) error
- 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 IsReservedPredictorName(name string) bool
- func MatchFeature(featureExpr string, activeFeatures map[string]bool) bool
- func NormalizeFeatureExpression(featureExpr string) string
- func ParseFeatureContainerEnv(containerTag reflect.StructTag) ([]string, bool)
- func ParseFeatureTag(feature string, required bool) (string, error)
- 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 SplitTagList(tag reflect.StructTag, key string) []string
- func TagCandidatesForRole(role string) ([]string, bool)
- func TextRangeParser[T cmp.Ordered](elemType reflect.Type) (func(string) (T, error), bool)
- 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 ValidatePredictorTag(tag reflect.StructTag, isBool bool, registeredNames []string, ...) error
- func ValidateScalarRange[T cmp.Ordered](rangeSpec *Range, boundKind string, parse func(string) (T, error)) error
- type Arg
- 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) 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 Directives
- type FeatureField
- type FieldTags
- type Flag
- type Options
- type PredictorKind
- type PredictorSpec
- type Range
- type RangeDomain
- type RawArgs
- type TagKind
- type TagSpec
- type TagSpecProvider
- type ValidationOptions
Constants ¶
const ( // DefaultHelpFlagHelp is the default description for the --help flag. DefaultHelpFlagHelp = "Show help for command" // DefaultHelpCommandHelp is the default description for the help subcommand. DefaultHelpCommandHelp = "Show help for a command" // DefaultVersionFlagHelp is the default description for the --version flag. DefaultVersionFlagHelp = "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.WhyJSON()). 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) // 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 BootstrapFeatureConflictError ¶
func BootstrapFeatureConflictError() error
BootstrapFeatureConflictError builds the schema error for a bootstrap field that is also feature-gated. The loader 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 BootstrapRequiresLoaderError ¶
func BootstrapRequiresLoaderError() error
BootstrapRequiresLoaderError builds the schema error for a bootstrap-tagged field under an app that never declares a configuration loader. 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 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 ConfigLoaderConfigFileConflictError ¶
ConfigLoaderConfigFileConflictError builds the error when conga.ConfigLoader() is combined with a root conga.ConfigFile field. The loader replaces file loading, so the config-file flag would never load a file. 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 ConfigLoaderDecoderConflictError ¶
func ConfigLoaderDecoderConflictError() error
ConfigLoaderDecoderConflictError builds the error when conga.ConfigLoader() is combined with a registered configuration decoder. With a loader there is no file loading, so decoders would be dead weight. 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 ConfigLoaderOptionsConflictError ¶
func ConfigLoaderOptionsConflictError() error
ConfigLoaderOptionsConflictError builds the error when conga.ConfigLoader() is combined with a file-based configuration option (conga.ConfigPaths, conga.ConfigExplicit, or conga.ConfigCascading). The loader replaces file discovery entirely, so the options would be silently ignored. 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 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 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 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 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 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 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 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 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 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 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").
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 Command ¶
type Command struct {
Name string
Aliases []string
Summary string
Description string
Examples string
Deprecated string
Group string
Hidden bool
EnvPrefix string
Version 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
Flags []*Flag
Args []*Arg
Subcommands []*Command
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.WhyJSON()). 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) FindShortFlag ¶
FindShortFlag returns the flag matching short rune r, or nil.
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) 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.WhyJSON()). 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
TargetShell string
}
CompleteOptions configures the execution of the completion engine.
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
// Loader reports that the application declared a programmatic
// configuration document source via conga.ConfigLoader(...). The loader
// function itself lives on the root conga.App; the marker rides here so
// runtime schema validation and the static analyzer can reject
// combinations with the file-based resolution settings and decoders.
Loader bool
}
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
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 Directives ¶
type Directives struct {
Ignore bool
}
Directives holds the parsed directives of a conga:"..." struct tag.
func ParseCongaDirectives ¶
func ParseCongaDirectives(congaTag string) (Directives, error)
ParseCongaDirectives parses the directives of a conga:"..." struct tag.
func ValidateFieldTags ¶
func ValidateFieldTags(tag reflect.StructTag, role string, candidates []string, opts ValidationOptions) (Directives, error)
ValidateFieldTags validates the struct tags of a single schema field: tag syntax, conga directives, 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. It returns the parsed conga directives so callers can honor conga:"ignore".
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
Short rune
Aliases []string
Default string
EnvVars []string
EnvExcluded bool
ConfigKey string
XorGroup string
AndGroup 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
Group 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, so ancestor flag shadowing validation
// exempts them: a same-named user flag on an ancestor stays reachable.
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 before the configuration
// loader runs and exposed to it 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 FindDeclaredFlagInChain ¶
FindDeclaredFlagInChain searches backwards through chain for a declared flag matching name or alias, without the built-in --help/--version fallback.
func FindFlagInChain ¶
FindFlagInChain searches backwards through chain for a flag matching name or alias, falling back to the built-in --help, --version, --completion, and --why flags.
func FindNegatableFlagInChain ¶
FindNegatableFlagInChain resolves the positive flag behind a `no-`-prefixed long flag token (e.g. --no-color resolving --color), enforcing the spec.CanNegate guard.
func FindShortFlagInChain ¶
FindShortFlagInChain searches backwards through chain for a flag matching short rune r.
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
// ConfigSettings carries the app-level configuration resolution settings
// (app.ConfigOptions options) onto the root command.
ConfigSettings ConfigSettings
ConfigCapable bool
DisableHelp bool
DisableVersion bool
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 or positional argument.
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
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 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 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.