spec

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 20, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package spec builds and validates command schemas from application structs.

Index

Constants

View Source
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.
	DefaultWhyFlagHelp = "Show resolved field values and where they came from (values redacted unless tagged safe); accepts text or 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"
)
View Source
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

View Source
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}
)
View Source
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

func BootstrapTagged(tag reflect.StructTag) bool

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

func CanNegate(flagSpec *Flag) bool

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

func CascadingRequiresMultiError(flagName string) error

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

func ConfigLoaderConfigFileConflictError(flagName string) error

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

func DefaultTypeHelp(targetType reflect.Type, tags FieldTags) string

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

func DuplicateFeatureError(name string, typeName string) error

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 FeatureFieldName

func FeatureFieldName(fieldName string, tag reflect.StructTag) (string, error)

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

func FeatureFieldTypeError(fieldName string, typeName string) error

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

func FeatureStageAllOrNothingError(fieldName string) error

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

func FeaturesAlreadyDeclaredError(firstFlagName string) error

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

func FieldTagKeys(tagSpecs []TagSpec) []string

FieldTagKeys returns the tag keys of tagSpecs for tag-candidate merging.

func IsReservedPredictorName

func IsReservedPredictorName(name string) bool

IsReservedPredictorName reports whether name is a reserved built-in predictor name or alias.

func MatchFeature

func MatchFeature(featureExpr string, activeFeatures map[string]bool) bool

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

func NormalizeFeatureExpression(featureExpr string) string

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 ParseFeatureTag

func ParseFeatureTag(feature string, required bool) (string, error)

ParseFeatureTag parses, validates, and normalizes the "feature" struct tag expression.

func ParseGlobPatterns

func ParseGlobPatterns(value string) ([]string, error)

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

func ParseStrictBoolTag(tag reflect.StructTag, key string) (bool, bool, error)

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

func ParseStrictStringTag(tag reflect.StructTag, tagSpec TagSpec) (string, bool, error)

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

func ParseSummaryTag(tag reflect.StructTag, defaultSummary string) (string, error)

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

func ProjectTextValue[T cmp.Ordered](elemType reflect.Type, value reflect.Value) (T, bool)

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 SplitTagList

func SplitTagList(tag reflect.StructTag, key string) []string

SplitTagList splits a comma-separated struct tag value into trimmed entries.

func TagCandidatesForRole

func TagCandidatesForRole(role string) ([]string, bool)

TagCandidatesForRole returns the allowed struct tag key candidates for a schema field role. The second result reports whether the role is known.

func TextRangeParser

func TextRangeParser[T cmp.Ordered](elemType reflect.Type) (func(string) (T, error), bool)

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

func ValidateConfigFileConfigTag(tag reflect.StructTag) error

ValidateConfigFileConfigTag rejects a config struct tag on a config file flag whose value is not "-".

func ValidateCountRangeSpec

func ValidateCountRangeSpec(spec *Range, tagName string) error

ValidateCountRangeSpec validates len/items range bounds as non-negative integers.

func ValidateCounterDefaultTag

func ValidateCounterDefaultTag(tag reflect.StructTag) error

ValidateCounterDefaultTag rejects a default struct tag on a counter flag.

func ValidateFeatureExpression

func ValidateFeatureExpression(featureExpr string) error

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

func ValidateFeatureReferences(root *Command) error

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, opts ValidationOptions, registeredNames []string) error

ValidatePredictorTag validates an explicit predictor:"..." struct tag without runtime predictor inference: built-in predictor vocabulary is always checked; custom predictor names only under strict tag validation.

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
	HelpFooter      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
	// 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
}

Command represents the metadata and AST definition of a command node.

func Build

func Build(target any, defaultName string, opts Options) (*Command, error)

Build inspects a struct pointer and recursively constructs the Command AST tree.

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

func (c *Command) CompletionFlagVisible(isRoot bool) bool

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

func (c *Command) FeatureNames() []string

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

func (c *Command) FindFlag(name string) *Flag

FindFlag returns the flag matching name or alias, or nil.

func (*Command) FindShortFlag

func (c *Command) FindShortFlag(r rune) *Flag

FindShortFlag returns the flag matching short rune r, or nil.

func (*Command) FindSubcommand

func (c *Command) FindSubcommand(name string) *Command

FindSubcommand returns the subcommand matching name or alias, or nil.

func (*Command) HasCompletionCommand

func (c *Command) HasCompletionCommand() bool

HasCompletionCommand reports whether this command contains a completion subcommand.

func (*Command) HasUserSubcommands

func (c *Command) HasUserSubcommands() bool

HasUserSubcommands returns true if this command has user-declared subcommands (excluding built-in help, version, and completion).

func (*Command) VersionFlagVisible

func (c *Command) VersionFlagVisible(isRoot bool) bool

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

func (c *Command) WhyFlagVisible() bool

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.

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
	AllowUnknownTags bool
	Recurse          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 — under strict tag validation — tag-key candidate membership for the field's role. It returns the parsed conga directives so callers can honor conga:"ignore" and allow-unknown-tags propagation.

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
	// 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

type FieldTags map[string]string

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

func ParseFieldTags(tag reflect.StructTag, tagSpecs []TagSpec) (FieldTags, error)

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.

func (FieldTags) Bool

func (t FieldTags) Bool(key string) bool

Bool reports whether the field declared the tag with a truthy value.

func (FieldTags) Has

func (t FieldTags) Has(key string) bool

Has reports whether the field declared the tag.

func (FieldTags) String

func (t FieldTags) String(key string) string

String returns the raw value of the declared tag, or "" when absent.

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

func FindDeclaredFlagInChain(chain []*Command, name string) *Flag

FindDeclaredFlagInChain searches backwards through chain for a declared flag matching name or alias, without the built-in --help/--version fallback.

func FindFlagInChain

func FindFlagInChain(chain []*Command, name string) *Flag

FindFlagInChain searches backwards through chain for a flag matching name or alias, falling back to the built-in --help and --version flags.

func FindNegatableFlagInChain

func FindNegatableFlagInChain(chain []*Command, name string) *Flag

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

func FindShortFlagInChain(chain []*Command, r rune) *Flag

FindShortFlagInChain searches backwards through chain for a flag matching short rune r.

type Options

type Options struct {
	StrictTagValidation     bool
	AllowUnknownTags        bool
	AllowUnknownTagsRecurse bool
	AllowedTags             []string
	RegisteredPredictors    map[string]predict.Predictor
	TypePredictors          map[reflect.Type]predict.Predictor
	ConfigFilePatterns      []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
	// 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

type Range struct {
	MinStr string
	MaxStr string
	HasMin bool
	HasMax bool
	Exact  bool
}

Range represents parsed range bounds for numeric, length, or collection constraints.

func ParseRangeSpec

func ParseRangeSpec(tag string) (*Range, error)

ParseRangeSpec parses a range tag value (min..max, min.., ..max, or exact).

func (*Range) HintText

func (r *Range) HintText() string

HintText renders the range's inline description without brackets ("1..10", ">= 5", "<= 9", or the exact value). It returns "" when no bound is declared.

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 {
	// StrictTagValidation enables unknown struct tag key checks.
	StrictTagValidation bool

	// AllowUnknownTags disables unknown struct tag key checks entirely
	// (conga:"allow-unknown-tags" directive equivalent).
	AllowUnknownTags bool

	// AllowedTags lists additional struct tag keys accepted under strict
	// tag validation (app.AllowTags equivalent).
	AllowedTags []string

	// 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.StrictTagValidation, app.AllowTags) instead of runtime reflection.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL