Documentation
¶
Index ¶
- Constants
- func RegisterFieldValidator(fv FieldValidator)
- func RegisterTagValidator(tv TagValidator)
- func RegisterTypeValidator(tv TypeValidator)
- type Conditions
- type Config
- type Context
- type FieldValidator
- type FunctionFlags
- type FunctionGen
- type FunctionLiteral
- type Identifier
- type LateTagValidator
- type Literal
- type ParamResult
- type PrivateVar
- type Scope
- type TagArgDoc
- type TagDoc
- type TagPayloadDoc
- type TagValidator
- type TypeValidator
- type Validations
- type Validator
- type VariableGen
- type WrapperFunction
Constants ¶
const (
ListMapKeyTagName = "k8s:listMapKey"
)
Variables ¶
This section is empty.
Functions ¶
func RegisterFieldValidator ¶ added in v0.34.0
func RegisterFieldValidator(fv FieldValidator)
RegisterFieldValidator must be called for a FieldValidator to be used by validation-gen. See FieldValidator for more information.
func RegisterTagValidator ¶
func RegisterTagValidator(tv TagValidator)
RegisterTagValidator must be called for TagValidator to be used by validation-gen. See TagValidator for more information.
func RegisterTypeValidator ¶
func RegisterTypeValidator(tv TypeValidator)
RegisterTypeValidator must be called for a TypeValidator to be used by validation-gen. See TypeValidator for more information.
Types ¶
type Conditions ¶
type Conditions struct { // OptionEnabled specifies an option name that must be set to true for the condition to be true. OptionEnabled string // OptionDisabled specifies an option name that must be set to false for the condition to be true. OptionDisabled string }
Conditions defines what conditions must be true for a resource to be validated. If any of the conditions are not true, the resource is not validated.
func (Conditions) Empty ¶
func (c Conditions) Empty() bool
type Config ¶
type Config struct { // GengoContext provides gengo's generator Context. This allows validators // to look up all sorts of other information. GengoContext *generator.Context // Validator provides a way to compose validations. // // For example, it is possible to define a validation such as // "+myValidator=+format=IP" by using the registry to extract the // validation for the embedded "+format=IP" and use those to // create the final Validations returned by the "+myValidator" tag. // // This field MUST NOT be used during init, since other validators may not // be initialized yet. Validator Validator }
Config carries optional configuration information for use by validators.
type Context ¶
type Context struct { // Scope is where the validation is being considered. Scope Scope // Type provides details about the type being validated. When Scope is // ScopeType, this is the newly defined type. When Scope is ScopeField, // this is the field's type (which may be a pointer, an alias, or both). // When Scope indicates a list-value, map-key, or map-value, this is the // type of that key or value (which, again, may be a pointer, and alias, or // both). Type *types.Type // ParentPath provides the field path to the parent type or field, enabling // unique identification of validation contexts for the same type in // different locations. ParentPath *field.Path // Member provides details about a field within a struct when Scope is // ScopeField. For all other values of Scope, this will be nil. Member *types.Member // Path provides the field path to the type or field being validated. This // is useful for identifying an exact context, e.g. to track information // between related tags. Path *field.Path }
Context describes where a tag was used, so that the scope can be checked and so validators can handle different cases if they need.
type FieldValidator ¶ added in v0.34.0
type FieldValidator interface { // Init initializes the implementation. This will be called exactly once. Init(cfg Config) // Name returns a unique name for this validator. This is used for sorting // and logging. Name() string // GetValidations returns any validations imposed by this validator for the // given context. // // The way gengo handles type definitions varies between structs and other // types. For struct definitions (e.g. `type Foo struct {}`), the realType // is the struct itself (the Kind field will be `types.Struct`) and the // parentType will be nil. For other types (e.g. `type Bar string`), the // realType will be the underlying type and the parentType will be the // newly defined type (the Kind field will be `types.Alias`). GetValidations(context Context) (Validations, error) }
FieldValidator describes a validator which runs on every field definition. To be findable by validation-gen, a FieldValidator must be registered - see RegisterFieldValidator.
FieldValidators are always processed after TagValidators and TypeValidators, and after the field has been fully processed (including all child fields). This means that they can "finish" work with data that was collected by TagValidators.
FieldValidators MUST NOT depend on other FieldValidators having been run already.
type FunctionFlags ¶
type FunctionFlags uint32
FunctionFlags define optional properties of a validator. Most validators can just use DefaultFlags.
const ( // DefaultFlags is defined for clarity. DefaultFlags FunctionFlags = 0 // ShortCircuit indicates that further validations should be skipped if // this validator fails. Most validators are not fatal. ShortCircuit FunctionFlags = 1 << iota // NonError indicates that a failure of this validator should not be // accumulated as an error, but should trigger other aspects of the failure // path (e.g. early return when combined with ShortCircuit). NonError )
func (FunctionFlags) IsSet ¶
func (ff FunctionFlags) IsSet(wanted FunctionFlags) bool
IsSet returns true if all of the wanted flags are set.
type FunctionGen ¶
type FunctionGen struct { // TagName is the tag which triggered this function. TagName string // Flags holds the options for this validator function. Flags FunctionFlags // Function is the name of the function to call. Function types.Name // Args holds arguments to pass to the function, and may conatin: // - data literals comprised of maps, slices, strings, ints, floats, and bools // - types.Type (to reference any type in the universe) // - types.Member (to reference members of the current value) // - types.Identifier (to reference any identifier in the universe) // - validators.WrapperFunction (to call another validation function) // - validators.Literal (to pass a literal value) // - validators.FunctionLiteral (to pass a function literal) // - validators.PrivateVar (to reference a variable) // // See toGolangSourceDataLiteral for details. Args []any // TypeArgs assigns types to the type parameters of the function, for // generic function calls which require explicit type arguments. TypeArgs []types.Name // Conditions holds any conditions that must true for a field to be // validated by this function. Conditions Conditions // Comments holds optional comments that should be added to the generated // code (without the leading "//"). Comments []string }
FunctionGen describes a function call that should be generated.
func Function ¶
func Function(tagName string, flags FunctionFlags, function types.Name, extraArgs ...any) FunctionGen
Function creates a FunctionGen for a given function name and extraArgs.
func (FunctionGen) WithComment ¶
func (fg FunctionGen) WithComment(comment string) FunctionGen
WithComment returns a new FunctionGen with a comment.
func (FunctionGen) WithConditions ¶
func (fg FunctionGen) WithConditions(conditions Conditions) FunctionGen
WithConditions returns a derived FunctionGen with conditions.
func (FunctionGen) WithTypeArgs ¶
func (fg FunctionGen) WithTypeArgs(typeArgs ...types.Name) FunctionGen
WithTypeArgs returns a derived FunctionGen with type arguments.
type FunctionLiteral ¶
type FunctionLiteral struct { Parameters []ParamResult Results []ParamResult Body string }
FunctionLiteral describes a function-literal expression that can be used as an argument to a validator. Unlike WrapperFunction, this does not necessarily have the same signature as a regular validation function.
type Identifier ¶
Identifier is a name that the generator will output as an identifier. Identifiers are generated using the RawNamer strategy.
type LateTagValidator ¶
type LateTagValidator interface {
LateTagValidator()
}
LateTagValidator is an optional extension to TagValidator. Any TagValidator which implements this interface will be evaluated after all TagValidators which do not.
type Literal ¶
type Literal string
Literal is a literal value that, when used as an argument to a validator, will be emitted without any further interpretation. Use this with caution, it will not be subject to Namers.
type ParamResult ¶
ParamResult represents a parameter or a result of a function.
type PrivateVar ¶
PrivateVar is a variable name that the generator will output as a private identifier. PrivateVars are generated using the PrivateNamer strategy.
type Scope ¶
type Scope string
Scope describes where a validation (or potential validation) is located.
const ( // ScopeAny indicates that a validator may be use in any context. This value // should never appear in a Context struct, since that indicates a // specific use. ScopeAny Scope = "anywhere" // ScopeType indicates a validation on a type definition, which applies to // all instances of that type. ScopeType Scope = "type definitions" // ScopeField indicates a validation on a particular struct field, which // applies only to that field of that struct. ScopeField Scope = "struct fields" // ScopeListVal indicates a validation which applies to all elements of a // list field or type. ScopeListVal Scope = "list values" // ScopeMapKey indicates a validation which applies to all keys of a map // field or type. ScopeMapKey Scope = "map keys" // ScopeMapVal indicates a validation which applies to all values of a map // field or type. ScopeMapVal Scope = "map values" )
Note: All of these values should be strings which can be used in an error message such as "may not be used in %s".
type TagArgDoc ¶
type TagArgDoc struct { // Name of this arg. Not provided for positional args. Name string // Description is a short description of this arg (e.g. `<name>`). Description string // Type is the type of the arg. Type codetags.ArgType // Required is true if the argument is required. Required bool // Default is the effective value if no value is provided. Default string // Docs is a human-oriented string explaining this arg. Docs string }
TagArgDoc describes an argument for a tag.
For example,
`+tagName(arg)` `+tagName(name1: arg1, name2: arg2)`
type TagDoc ¶
type TagDoc struct { // Tag is the tag name, without the leading '+'. Tag string // Args lists any arguments this tag might take. Args []TagArgDoc // Usage is how the tag is used, including arguments. Usage string // Description is a short description of this tag's purpose. Description string // Docs is a human-oriented string explaining this tag. Docs string // Scopes lists the place or places this tag may be used. Scopes []Scope // Payloads lists zero or more varieties of value for this tag. If this tag // never has a payload, this list should be empty, but if the payload is // optional, this list should include an entry for "<none>". Payloads []TagPayloadDoc // PayloadsType is the type of the payloads. PayloadsType codetags.ValueType // PayloadsRequired is true if a payload is required. PayloadsRequired bool // AcceptsUnknownArgs is true if unknown args are accepted AcceptsUnknownArgs bool }
TagDoc describes a comment-tag and its usage.
type TagPayloadDoc ¶
type TagPayloadDoc struct { // Description is a short description of this payload (e.g. `<number>`). Description string // Docs is a human-oriented string explaining this payload. Docs string }
TagPayloadDoc describes a value for a tag (e.g. `+tagName=tagValue`). Some tags support multiple payloads, including <none> (e.g. `+tagName`).
type TagValidator ¶
type TagValidator interface { // Init initializes the implementation. This will be called exactly once. Init(cfg Config) // TagName returns the full tag name (without the "marker" prefix) for this // tag. TagName() string // ValidScopes returns the set of scopes where this tag may be used. ValidScopes() sets.Set[Scope] // GetValidations returns any validations described by this tag. GetValidations(context Context, tag codetags.Tag) (Validations, error) // Docs returns user-facing documentation for this tag. Docs() TagDoc }
TagValidator describes a single validation tag and how to use it. To be findable by validation-gen, a TagValidator must be registered - see RegisterTagValidator.
TagValidators are always evaluated before TypeValidators and FieldValidators. In general, TagValidators should not depend on other TagValidators having been run already because users might specify tags in the any order. The one exception to this rule is that some TagValidators may be designated as "late" validators (see LateTagValidator), which means they will be run after all non-late TagValidators.
No other guarantees are made about the order of execution of TagValidators or LateTagValidators. Instead of relying on tag ordering, TagValidators can accumulate information internally and use a TypeValidator and/or FieldValidator to finish the work.
type TypeValidator ¶
type TypeValidator interface { // Init initializes the implementation. This will be called exactly once. Init(cfg Config) // Name returns a unique name for this validator. This is used for sorting // and logging. Name() string // GetValidations returns any validations imposed by this validator for the // given context. // // The way gengo handles type definitions varies between structs and other // types. For struct definitions (e.g. `type Foo struct {}`), the realType // is the struct itself (the Kind field will be `types.Struct`) and the // parentType will be nil. For other types (e.g. `type Bar string`), the // realType will be the underlying type and the parentType will be the // newly defined type (the Kind field will be `types.Alias`). GetValidations(context Context) (Validations, error) }
TypeValidator describes a validator which runs on every type definition. To be findable by validation-gen, a TypeValidator must be registered - see RegisterTypeValidator.
TypeValidators are always processed after TagValidators, and after the type has been fully processed (including all child fields and their types). This means that they can "finish" work with data that was collected by TagValidators.
TypeValidators MUST NOT depend on other TypeValidators having been run already.
type Validations ¶
type Validations struct { // Functions hold the function calls that should be generated to perform // validation. These functions may not be called in order - they may be // sorted based on their flags and other criteria. // // Each function's signature must be of the form: // func( // // standard arguments // ctx context.Context // op operation.Operation, // fldPath field.Path, // value, oldValue <ValueType>, // always nilable // // additional arguments (optional) // Args[0] <Args[0]Type>, // Args[1] <Args[1]Type>, // ... // Args[N] <Args[N]Type>) // // The standard arguments are not included in the FunctionGen.Args list. Functions []FunctionGen // Variables hold any variables which must be generated to perform // validation. Variables are not permitted in every context. Variables []VariableGen // Comments holds comments to emit (without the leading "//"). Comments []string // OpaqueType indicates that the type being validated is opaque, and that // any validations defined on it should not be emitted. OpaqueType bool // OpaqueKeyType indicates that the key type of a map being validated is // opaque, and that any validations defined on it should not be emitted. OpaqueKeyType bool // OpaqueValType indicates that the key type of a map or slice being // validated is opaque, and that any validations defined on it should not // be emitted. OpaqueValType bool }
Validations define the function calls and variables to generate to perform validation.
func ForEachKey ¶
func ForEachKey(_ *field.Path, t *types.Type, fn FunctionGen) (Validations, error)
ForEachKey returns a validation that applies a function to each key of a map.
func ForEachVal ¶
func ForEachVal(fldPath *field.Path, t *types.Type, fn FunctionGen) (Validations, error)
ForEachVal returns a validation that applies a function to each element of a list or map. The type argument is expected to be the top-most type of the list or map. For example, if this is a typedef to a list, this is the alias type, not the underlying type.
func (*Validations) Add ¶
func (v *Validations) Add(o Validations)
func (*Validations) AddComment ¶
func (v *Validations) AddComment(comment string)
func (*Validations) AddFunction ¶
func (v *Validations) AddFunction(fn FunctionGen)
func (*Validations) AddVariable ¶
func (v *Validations) AddVariable(vr VariableGen)
func (*Validations) Empty ¶
func (v *Validations) Empty() bool
func (*Validations) Len ¶
func (v *Validations) Len() int
type Validator ¶
type Validator interface { // ExtractTags extracts Tags from comment lines. ExtractTags(context Context, comments []string) ([]codetags.Tag, error) // ExtractValidations considers the given context (e.g. a type definition) and // evaluates registered validators. This includes type validators (which run // against all types) and tag validators which run only if a specific tag is // found in the associated comment block. Any matching validators produce zero // or more validations, which will later be rendered by the code-generation // logic. ExtractValidations(context Context, Tags ...codetags.Tag) (Validations, error) // Docs returns documentation for each known tag. Docs() []TagDoc }
Validator represents an aggregation of validator plugins.
func InitGlobalValidator ¶
InitGlobalValidator must be called exactly once by the main application to initialize and safely access the global tag registry. Once this is called, no more validators may be registered.
type VariableGen ¶
type VariableGen struct { // Variable holds the variable identifier. Variable PrivateVar // InitFunc describes the function call that the variable is assigned to. InitFunc FunctionGen }
func Variable ¶
func Variable(variable PrivateVar, initFunc FunctionGen) VariableGen
Variable creates a VariableGen for a given function name and extraArgs.
type WrapperFunction ¶
type WrapperFunction struct { Function FunctionGen ObjType *types.Type }
WrapperFunction describes a function literal which has the fingerprint of a regular validation function (op, fldPath, obj, oldObj) and calls another validation function with the same signature, plus extra args if needed.