Documentation
¶
Overview ¶
Package yamlvalidator provides a flexible YAML validation library with support for type checking, custom validators, conditional logic, and detailed error reporting with source context.
Index ¶
- Variables
- func AppendIndexPath(base string, index int) (string, error)
- func AppendPropertyPath(base, property string) string
- func FormatErrorWithSource(err ValidationError, lines []string) string
- func FormatPathTokens(tokens []PathToken) string
- func Ptr[T any](v T) *T
- func RenderLineWithCaret(line string, byteCol int) (string, int, int)
- func ValidateFieldSchema(schema *FieldSchema) error
- type ConditionalRule
- type DefinitionValidator
- type DependencyDetails
- type ErrorCollector
- type ErrorLevel
- type FieldSchema
- func CompileJSONSchema(data []byte) (*FieldSchema, error)
- func CompileJSONSchemaContext(ctx context.Context, data []byte) (*FieldSchema, error)
- func CompileJSONSchemaContextWithOptions(ctx context.Context, data []byte, opts JSONSchemaCompileOptions) (*FieldSchema, error)
- func CompileJSONSchemaWithOptions(data []byte, opts JSONSchemaCompileOptions) (*FieldSchema, error)
- type ItemCountDetails
- type JSONSchemaCachingResolver
- type JSONSchemaCompileOptions
- type JSONSchemaContentEncoding
- type JSONSchemaContentMediaType
- type JSONSchemaDraft
- type JSONSchemaFileResolver
- type JSONSchemaFormat
- type JSONSchemaKeyword
- type JSONSchemaKeywordCompileContext
- type JSONSchemaKeywordCompileContextFunc
- type JSONSchemaKeywordCompileFunc
- type JSONSchemaKeywordFunc
- type JSONSchemaKeywordValidateFunc
- type JSONSchemaKeywordValidationContext
- func (ctx *JSONSchemaKeywordValidationContext) AddError(message string)
- func (ctx *JSONSchemaKeywordValidationContext) AddErrorAt(path []string, message string)
- func (ctx *JSONSchemaKeywordValidationContext) MarkItemEvaluated(index int)
- func (ctx *JSONSchemaKeywordValidationContext) MarkPropertyEvaluated(name string)
- func (ctx *JSONSchemaKeywordValidationContext) ValidateSubschema(schema *JSONSchemaSubschema, instance any, relativePath []string) bool
- type JSONSchemaResolver
- type JSONSchemaResolverChain
- type JSONSchemaResolverFunc
- type JSONSchemaResourceMap
- type JSONSchemaSubschema
- type JSONSchemaSubschemaPath
- type JSONSchemaSubschemaPosition
- type JSONSchemaVocabulary
- type KeyValidator
- type KeyValidatorCloner
- type NodeType
- type NumericRangeDetails
- type PathToken
- type PathTokenKind
- type RequiredDetails
- type TypeMismatchDetails
- type UnknownKeyDetails
- type UnknownKeyPolicy
- type ValidationContext
- type ValidationError
- type ValidationResult
- type Validator
- func (v *Validator) ValidateBytes(data []byte) *ValidationResult
- func (v *Validator) ValidateContext(runCtx context.Context, data []byte) (*ValidationResult, error)
- func (v *Validator) ValidateContextWithOptions(runCtx context.Context, data []byte, opts ValidationContext) (*ValidationResult, error)
- func (v *Validator) ValidateReader(reader io.Reader) (*ValidationResult, error)
- func (v *Validator) ValidateReaderContext(runCtx context.Context, reader io.Reader) (*ValidationResult, error)
- func (v *Validator) ValidateReaderContextWithOptions(runCtx context.Context, reader io.Reader, opts ValidationContext) (*ValidationResult, error)
- func (v *Validator) ValidateReaderWithOptions(reader io.Reader, opts ValidationContext) (*ValidationResult, error)
- func (v *Validator) ValidateWithOptions(data []byte, opts ValidationContext) *ValidationResult
- type ValueValidator
- type ValueValidatorCloner
Constants ¶
This section is empty.
Variables ¶
var ErrJSONSchemaResourceNotFound = errors.New("JSON Schema resource not found")
ErrJSONSchemaResourceNotFound allows resolver chains to distinguish a miss from an actual resolver failure.
var ErrJSONSchemaResourceOutsideRoot = errors.New("JSON Schema resource is outside resolver root")
ErrJSONSchemaResourceOutsideRoot is returned by JSONSchemaFileResolver when a file URL escapes its configured root.
Functions ¶
func AppendIndexPath ¶ added in v0.6.0
AppendIndexPath appends a non-negative sequence index to a stable display path. It returns an error for negative indexes.
func AppendPropertyPath ¶ added in v0.6.0
AppendPropertyPath appends a mapping property to a stable display path. Ambiguous property names are quoted automatically.
func FormatErrorWithSource ¶
func FormatErrorWithSource(err ValidationError, lines []string) string
FormatErrorWithSource formats an error with source context. Correctly handles tabs and Unicode.
func FormatPathTokens ¶ added in v0.4.0
FormatPathTokens formats typed path tokens using the library's stable display syntax.
func Ptr ¶
func Ptr[T any](v T) *T
Ptr returns a pointer to the value. Useful for setting Min/Max fields.
func RenderLineWithCaret ¶
RenderLineWithCaret is an exported wrapper useful for external tests and tools.
func ValidateFieldSchema ¶ added in v0.3.0
func ValidateFieldSchema(schema *FieldSchema) error
ValidateFieldSchema checks FieldSchema invariants, including nested schemas, invalid constraints, recursive schema graphs, and validator definitions.
Types ¶
type ConditionalRule ¶
type ConditionalRule struct {
// ConditionField is the field to check.
ConditionField string
// ConditionValue is the expected value (scalar comparison).
ConditionValue string
// ThenRequired lists fields that become required when condition is met.
ThenRequired []string
// ThenForbidden lists fields that are forbidden when condition is met.
ThenForbidden []string
}
ConditionalRule defines conditional validation logic. When ConditionField equals ConditionValue, additional requirements apply.
type DefinitionValidator ¶ added in v0.3.0
type DefinitionValidator interface {
ValidateDefinition() error
}
DefinitionValidator may be implemented by value/key validators that can validate their own configuration during FieldSchema compilation.
type DependencyDetails ¶ added in v0.4.0
DependencyDetails describes a field required by another field.
type ErrorCollector ¶
type ErrorCollector struct {
// contains filtered or unexported fields
}
ErrorCollector accumulates validation errors and warnings.
func NewErrorCollector ¶
func NewErrorCollector() *ErrorCollector
NewErrorCollector creates a new empty ErrorCollector.
func (*ErrorCollector) Add ¶
func (c *ErrorCollector) Add(err ValidationError)
Add adds a validation error to the collector.
func (*ErrorCollector) All ¶
func (c *ErrorCollector) All() []ValidationError
All returns a defensive copy of all diagnostics in insertion order.
func (*ErrorCollector) Errors ¶
func (c *ErrorCollector) Errors() []ValidationError
Errors returns a defensive copy of all errors.
func (*ErrorCollector) HasErrors ¶
func (c *ErrorCollector) HasErrors() bool
HasErrors returns true if there are any errors (not warnings).
func (*ErrorCollector) Warnings ¶
func (c *ErrorCollector) Warnings() []ValidationError
Warnings returns a defensive copy of all warnings.
type ErrorLevel ¶
type ErrorLevel int
ErrorLevel defines the severity of a validation error.
const ( // LevelWarning indicates a non-critical issue (e.g., deprecated field, unknown key in permissive mode). LevelWarning ErrorLevel = iota // LevelError indicates a critical validation failure. LevelError )
func (ErrorLevel) String ¶
func (l ErrorLevel) String() string
type FieldSchema ¶
type FieldSchema struct {
// Type is the expected node type.
Type NodeType
// AllowedTypes accepts any of the listed node types. When non-empty it
// takes precedence over Type and is useful for schema unions.
AllowedTypes []NodeType
// Required indicates the field must be present.
Required bool
// Nullable allows null values even when Type is not TypeNull.
Nullable bool
// Deprecated contains a deprecation message (empty = not deprecated).
// Use "true" for a generic message.
Deprecated string
// Description is a human-readable field description.
Description string
// Default is the default value. If set and field is missing, a warning is emitted.
Default interface{}
// AllowedKeys defines known keys and their schemas.
// If nil, ALL keys are considered unknown.
// This does NOT mean "don't check" - it means "no known keys".
//
// For "any keys allowed, no validation":
// AllowedKeys: nil,
// AdditionalProperties: &FieldSchema{Type: TypeAny},
//
// For "don't touch this map at all":
// AllowedKeys: nil,
// AdditionalProperties: nil,
// UnknownKeyPolicy: UnknownKeyIgnore,
AllowedKeys map[string]*FieldSchema
// AdditionalProperties is the schema for keys not in AllowedKeys.
// If not nil: unknown keys are allowed and validated against this schema.
// If nil: unknown keys are handled by UnknownKeyPolicy.
AdditionalProperties *FieldSchema
// UnknownKeyPolicy determines handling of keys not in AllowedKeys
// when AdditionalProperties is nil.
UnknownKeyPolicy UnknownKeyPolicy
// KeyValidators validate key names (applied to ALL keys).
KeyValidators []KeyValidator
// ItemSchema is the schema for sequence items.
ItemSchema *FieldSchema
// MinItems is the minimum number of items (nil = no limit).
MinItems *int
// MaxItems is the maximum number of items (nil = no limit).
MaxItems *int
// Validators are custom value validators.
Validators []ValueValidator
// AnyOf requires at least one field group to be fully present.
// Example: [][]string{{"configFile"}, {"host", "port"}}
// Means: either configFile, OR both host AND port.
AnyOf [][]string
// ExactlyOneOf requires exactly one field from the list.
// Example: []string{"inline", "file", "url"}
// Means: exactly one of inline/file/url must be present.
ExactlyOneOf []string
// MutuallyExclusive allows at most one field from the list (zero is OK).
// Example: []string{"debug", "quiet"}
// Means: debug and quiet cannot both be present.
MutuallyExclusive []string
// Conditions define conditional validation rules.
Conditions []ConditionalRule
// OneOfSchemas requires exactly one child schema to validate successfully.
OneOfSchemas []*FieldSchema
// AnyOfSchemas requires at least one child schema to validate successfully.
AnyOfSchemas []*FieldSchema
// OneOfRequired requires exactly one field group to be fully present.
OneOfRequired [][]string
// ForbiddenTogether rejects groups whose fields are all present together.
ForbiddenTogether [][]string
// DependentRequired requires additional fields when a trigger field is present.
DependentRequired map[string][]string
}
FieldSchema defines the validation rules for a field.
func CompileJSONSchema ¶ added in v0.3.0
func CompileJSONSchema(data []byte) (*FieldSchema, error)
CompileJSONSchema compiles a JSON Schema using draft 2020-12 as the default dialect. Schemas declaring $schema are compiled using their declared dialect.
func CompileJSONSchemaContext ¶ added in v0.5.0
func CompileJSONSchemaContext(ctx context.Context, data []byte) (*FieldSchema, error)
CompileJSONSchemaContext is the context-aware form of CompileJSONSchema. Context cancellation is observed by library-controlled compilation work and by JSONSchemaResolver implementations.
func CompileJSONSchemaContextWithOptions ¶ added in v0.5.0
func CompileJSONSchemaContextWithOptions( ctx context.Context, data []byte, opts JSONSchemaCompileOptions, ) (*FieldSchema, error)
CompileJSONSchemaContextWithOptions is the context-aware form of CompileJSONSchemaWithOptions.
func CompileJSONSchemaWithOptions ¶ added in v0.3.0
func CompileJSONSchemaWithOptions(data []byte, opts JSONSchemaCompileOptions) (*FieldSchema, error)
CompileJSONSchemaWithOptions compiles a standards-compliant JSON Schema and returns a FieldSchema adapter that validates YAML through the JSON Schema engine while preserving YAML source positions in diagnostics.
type ItemCountDetails ¶ added in v0.4.0
ItemCountDetails describes a sequence length failure.
type JSONSchemaCachingResolver ¶ added in v0.5.0
type JSONSchemaCachingResolver struct {
// contains filtered or unexported fields
}
JSONSchemaCachingResolver caches successful resolutions. Returned byte slices are defensive copies.
func NewJSONSchemaCachingResolver ¶ added in v0.5.0
func NewJSONSchemaCachingResolver(resolver JSONSchemaResolver) *JSONSchemaCachingResolver
NewJSONSchemaCachingResolver wraps resolver with a concurrency-safe cache.
type JSONSchemaCompileOptions ¶ added in v0.3.0
type JSONSchemaCompileOptions struct {
// SchemaURL is the retrieval URL of the root schema. It is used as the base
// URI for relative references when the schema does not establish another base
// with $id. The default is an in-memory HTTPS URL.
SchemaURL string
// DefaultDraft is used only when the schema does not contain $schema.
// The default is draft 2020-12.
DefaultDraft JSONSchemaDraft
// AssertFormat forces format to be an assertion even in dialects where it is
// annotation-only by default.
AssertFormat bool
// AssertContent enables contentEncoding/contentMediaType/contentSchema assertions.
AssertContent bool
// AssertVocabs requires vocabularies declared by a metaschema to be known.
AssertVocabs bool
// RegexpTimeout bounds one ECMAScript regexp match. Zero preserves the
// regexp engine's unlimited default. Use a positive duration for untrusted schemas.
RegexpTimeout time.Duration
// Formats registers first-class functional custom formats.
Formats []JSONSchemaFormat
// ContentEncodings registers custom contentEncoding decoders.
ContentEncodings []JSONSchemaContentEncoding
// ContentMediaTypes registers custom contentMediaType validators.
ContentMediaTypes []JSONSchemaContentMediaType
// Keywords registers functional custom keywords in an internal vocabulary.
// They are activated for this compilation automatically.
Keywords []JSONSchemaKeyword
// Vocabularies registers named functional custom vocabularies. They are
// activated for this compilation automatically.
Vocabularies []JSONSchemaVocabulary
// Resources preloads external resources addressed by their retrieval URLs.
// This is the preferred way to compile a closed schema graph without I/O.
Resources map[string][]byte
// Resolver resolves unresolved external references. If nil, compilation is
// closed-world: only the root schema, Resources, and built-in metaschemas are
// available. No filesystem or network I/O is performed implicitly.
Resolver JSONSchemaResolver
// AdditionalPropertiesFalsePolicy optionally downgrades direct
// additionalProperties:false diagnostics. This is a presentation policy and
// intentionally does not rewrite JSON Schema combinator semantics.
AdditionalPropertiesFalsePolicy *UnknownKeyPolicy
}
JSONSchemaCompileOptions controls JSON Schema compilation and validation.
type JSONSchemaContentEncoding ¶ added in v0.6.0
JSONSchemaContentEncoding registers a custom JSON Schema contentEncoding.
type JSONSchemaContentMediaType ¶ added in v0.6.0
type JSONSchemaContentMediaType struct {
Name string
Validate func([]byte) error
UnmarshalJSON func([]byte) (any, error)
}
JSONSchemaContentMediaType registers a custom JSON Schema contentMediaType. UnmarshalJSON is optional and should be set only when the media type contains a JSON-compatible data model that contentSchema may validate.
type JSONSchemaDraft ¶ added in v0.3.0
type JSONSchemaDraft string
JSONSchemaDraft selects the default JSON Schema dialect used when a schema does not declare $schema. An explicit $schema in the document takes precedence.
const ( JSONSchemaDraft4 JSONSchemaDraft = "draft-04" JSONSchemaDraft6 JSONSchemaDraft = "draft-06" JSONSchemaDraft7 JSONSchemaDraft = "draft-07" JSONSchemaDraft2019 JSONSchemaDraft = "2019-09" JSONSchemaDraft2020 JSONSchemaDraft = "2020-12" )
type JSONSchemaFileResolver ¶ added in v0.5.0
type JSONSchemaFileResolver struct {
// contains filtered or unexported fields
}
JSONSchemaFileResolver resolves file:// resources confined to one directory. The root must exist when the resolver is created.
func NewJSONSchemaFileResolver ¶ added in v0.5.0
func NewJSONSchemaFileResolver(root string) (*JSONSchemaFileResolver, error)
NewJSONSchemaFileResolver creates a file resolver constrained to root.
type JSONSchemaFormat ¶ added in v0.3.0
JSONSchemaFormat registers a custom JSON Schema format without exposing the underlying JSON Schema engine API.
type JSONSchemaKeyword ¶ added in v0.3.0
type JSONSchemaKeyword struct {
Name string
Validate JSONSchemaKeywordFunc
Compile JSONSchemaKeywordCompileFunc
CompileWithContext JSONSchemaKeywordCompileContextFunc
Subschemas []JSONSchemaSubschemaPath
}
JSONSchemaKeyword defines one custom JSON Schema keyword. Set exactly one of Validate, Compile, or CompileWithContext. Subschemas declares locations of nested schemas relative to the keyword value.
type JSONSchemaKeywordCompileContext ¶ added in v0.5.0
type JSONSchemaKeywordCompileContext struct {
// contains filtered or unexported fields
}
JSONSchemaKeywordCompileContext exposes high-level helpers needed by custom keywords which contain nested schemas.
func (*JSONSchemaKeywordCompileContext) Reference ¶ added in v0.5.0
func (ctx *JSONSchemaKeywordCompileContext) Reference(ref string) (*JSONSchemaSubschema, error)
Reference compiles a schema reference using the current schema resource.
func (*JSONSchemaKeywordCompileContext) Subschema ¶ added in v0.5.0
func (ctx *JSONSchemaKeywordCompileContext) Subschema(path ...string) *JSONSchemaSubschema
Subschema compiles a nested schema located at path relative to the custom keyword value. Path components are JSON object keys or array indexes encoded as decimal strings.
type JSONSchemaKeywordCompileContextFunc ¶ added in v0.5.0
type JSONSchemaKeywordCompileContextFunc func( ctx *JSONSchemaKeywordCompileContext, keywordValue any, ) (JSONSchemaKeywordValidateFunc, error)
JSONSchemaKeywordCompileContextFunc is the advanced high-level compile form for keywords that contain nested schemas or schema references.
type JSONSchemaKeywordCompileFunc ¶ added in v0.3.0
type JSONSchemaKeywordCompileFunc func( keywordValue any, ) (JSONSchemaKeywordValidateFunc, error)
JSONSchemaKeywordCompileFunc compiles a keyword value from the schema into a runtime validation function. It is useful for parsing/validating keyword configuration once instead of on every validation call.
type JSONSchemaKeywordFunc ¶ added in v0.3.0
type JSONSchemaKeywordFunc func( keywordValue any, instance any, ctx *JSONSchemaKeywordValidationContext, )
JSONSchemaKeywordFunc is the simple custom-keyword form. The schema keyword value and current JSON instance value are supplied on each validation call.
type JSONSchemaKeywordValidateFunc ¶ added in v0.3.0
type JSONSchemaKeywordValidateFunc func( instance any, ctx *JSONSchemaKeywordValidationContext, )
JSONSchemaKeywordValidateFunc validates one JSON instance value.
type JSONSchemaKeywordValidationContext ¶ added in v0.3.0
type JSONSchemaKeywordValidationContext struct {
// contains filtered or unexported fields
}
JSONSchemaKeywordValidationContext collects custom keyword diagnostics and evaluation annotations during one keyword validation call.
func (*JSONSchemaKeywordValidationContext) AddError ¶ added in v0.3.0
func (ctx *JSONSchemaKeywordValidationContext) AddError(message string)
AddError reports an error for the current instance value.
func (*JSONSchemaKeywordValidationContext) AddErrorAt ¶ added in v0.3.0
func (ctx *JSONSchemaKeywordValidationContext) AddErrorAt(path []string, message string)
AddErrorAt reports an error at a path relative to the current instance value.
func (*JSONSchemaKeywordValidationContext) MarkItemEvaluated ¶ added in v0.3.0
func (ctx *JSONSchemaKeywordValidationContext) MarkItemEvaluated(index int)
MarkItemEvaluated marks an array item as evaluated for unevaluatedItems semantics.
func (*JSONSchemaKeywordValidationContext) MarkPropertyEvaluated ¶ added in v0.3.0
func (ctx *JSONSchemaKeywordValidationContext) MarkPropertyEvaluated(name string)
MarkPropertyEvaluated marks an object property as evaluated for unevaluatedProperties semantics.
func (*JSONSchemaKeywordValidationContext) ValidateSubschema ¶ added in v0.5.0
func (ctx *JSONSchemaKeywordValidationContext) ValidateSubschema( schema *JSONSchemaSubschema, instance any, relativePath []string, ) bool
ValidateSubschema validates instance with a nested schema and reports any resulting JSON Schema errors through the current validation context. relativePath is relative to the current instance value.
type JSONSchemaResolver ¶ added in v0.5.0
JSONSchemaResolver resolves an absolute JSON Schema retrieval URL. Implementations must be safe for concurrent use if a compile configuration is reused concurrently.
type JSONSchemaResolverChain ¶ added in v0.5.0
type JSONSchemaResolverChain []JSONSchemaResolver
JSONSchemaResolverChain tries resolvers in order. Only ErrJSONSchemaResourceNotFound advances to the next resolver. Treat the slice as immutable while it is in use.
type JSONSchemaResolverFunc ¶ added in v0.5.0
JSONSchemaResolverFunc adapts a function to JSONSchemaResolver.
type JSONSchemaResourceMap ¶ added in v0.5.0
JSONSchemaResourceMap is an in-memory resolver keyed by absolute retrieval URL. Treat the map as immutable while it is in use; resolved byte slices are copied.
type JSONSchemaSubschema ¶ added in v0.5.0
type JSONSchemaSubschema struct {
// contains filtered or unexported fields
}
JSONSchemaSubschema is a compiled nested schema used by custom keywords. Its implementation is intentionally opaque so callers do not depend on the underlying JSON Schema engine.
type JSONSchemaSubschemaPath ¶ added in v0.5.0
type JSONSchemaSubschemaPath []JSONSchemaSubschemaPosition
JSONSchemaSubschemaPath declares a nested schema location relative to a custom keyword value.
type JSONSchemaSubschemaPosition ¶ added in v0.5.0
type JSONSchemaSubschemaPosition struct {
// contains filtered or unexported fields
}
JSONSchemaSubschemaPosition identifies one possible nested-schema location inside a custom keyword value. Use the constructor functions below.
func JSONSchemaSubschemaAllItems ¶ added in v0.5.0
func JSONSchemaSubschemaAllItems() JSONSchemaSubschemaPosition
JSONSchemaSubschemaAllItems selects all array items.
func JSONSchemaSubschemaAllProperties ¶ added in v0.5.0
func JSONSchemaSubschemaAllProperties() JSONSchemaSubschemaPosition
JSONSchemaSubschemaAllProperties selects all object property values.
func JSONSchemaSubschemaItem ¶ added in v0.5.0
func JSONSchemaSubschemaItem(index int) JSONSchemaSubschemaPosition
JSONSchemaSubschemaItem selects one array item.
func JSONSchemaSubschemaProperty ¶ added in v0.5.0
func JSONSchemaSubschemaProperty(name string) JSONSchemaSubschemaPosition
JSONSchemaSubschemaProperty selects one object property.
type JSONSchemaVocabulary ¶ added in v0.3.0
type JSONSchemaVocabulary struct {
URL string
// Schema optionally validates the custom keyword declarations introduced by
// this vocabulary. It must be a self-contained JSON Schema (standard
// metaschema references are supported).
Schema []byte
Keywords []JSONSchemaKeyword
}
JSONSchemaVocabulary groups custom keywords under a vocabulary URL. Vocabularies registered through JSONSchemaCompileOptions are activated for that compilation.
type KeyValidator ¶
type KeyValidator interface {
ValidateKey(key string, keyNode *yaml.Node, path string, ctx *ValidationContext)
}
KeyValidator validates key names in mappings. The same concurrency contract as ValueValidator applies to stateful implementations.
type KeyValidatorCloner ¶ added in v0.4.0
type KeyValidatorCloner interface {
CloneKeyValidator() KeyValidator
}
KeyValidatorCloner is the key-validator counterpart of ValueValidatorCloner.
type NodeType ¶
type NodeType int
NodeType represents the expected YAML node type.
const ( // TypeAny accepts any type. TypeAny NodeType = iota // TypeNull represents null/nil values. TypeNull // TypeString represents string values. TypeString // TypeInt represents integer values. TypeInt // TypeFloat represents floating-point values (also accepts int). TypeFloat // TypeBool represents boolean values. TypeBool // TypeMap represents mapping nodes. TypeMap // TypeSequence represents sequence/array nodes. TypeSequence )
func InferNodeType ¶ added in v0.6.0
func InferNodeType(node *yaml.Node, ctx *ValidationContext) NodeType
InferNodeType applies the same YAML type inference used by FieldSchema validation. A nil context uses default type-inference settings.
type NumericRangeDetails ¶ added in v0.4.0
NumericRangeDetails describes a numeric bound failure.
type PathToken ¶ added in v0.4.0
type PathToken struct {
Kind PathTokenKind
Name string
Index int
}
PathToken is one typed component of ValidationError.Path.
func ParsePathTokens ¶ added in v0.4.0
ParsePathTokens parses the library's display path syntax into typed tokens.
type PathTokenKind ¶ added in v0.4.0
type PathTokenKind string
PathTokenKind identifies one component of a structured validation path.
const ( PathTokenProperty PathTokenKind = "property" PathTokenIndex PathTokenKind = "index" // PathTokenDocument represents the reserved leading doc[N] prefix used for // multi-document YAML diagnostics. PathTokenDocument PathTokenKind = "document" )
type RequiredDetails ¶ added in v0.4.0
type RequiredDetails struct {
Field string
}
RequiredDetails describes a missing required field/property.
type TypeMismatchDetails ¶ added in v0.4.0
TypeMismatchDetails describes a type validation failure.
type UnknownKeyDetails ¶ added in v0.4.0
UnknownKeyDetails describes an unknown mapping key and optional suggestion.
type UnknownKeyPolicy ¶
type UnknownKeyPolicy int
UnknownKeyPolicy determines how unknown keys in maps are handled.
const ( // UnknownKeyInherit uses ctx.StrictKeys to decide: // StrictKeys=true -> error // StrictKeys=false -> warning UnknownKeyInherit UnknownKeyPolicy = iota // UnknownKeyError treats unknown keys as errors. UnknownKeyError // UnknownKeyWarn treats unknown keys as warnings. UnknownKeyWarn // UnknownKeyIgnore silently ignores unknown keys. UnknownKeyIgnore )
type ValidationContext ¶
type ValidationContext struct {
// StrictKeys determines the default behavior for unknown keys
// when UnknownKeyPolicy is UnknownKeyInherit:
// true -> unknown keys are errors
// false -> unknown keys are warnings
StrictKeys bool
// StopOnFirst stops validation after the first error.
StopOnFirst bool
// StrictTypes uses only YAML tags for type inference.
// When false, values are parsed to infer types (e.g., "123" -> int).
StrictTypes bool
// YAML11Booleans enables YAML 1.1 boolean literals (yes/no/on/off).
// By default, only YAML 1.2 booleans (true/false) are recognized.
YAML11Booleans bool
// MaxBytes rejects inputs larger than this many bytes. Zero means unlimited.
MaxBytes int
// MaxDocuments limits the number of YAML documents in a stream. Zero means unlimited.
MaxDocuments int
// MaxDepth limits YAML container/schema traversal depth. The root value has depth 1.
// Zero means unlimited.
MaxDepth int
// MaxDiagnostics stops validation after this many errors/warnings. Zero means unlimited.
MaxDiagnostics int
// contains filtered or unexported fields
}
ValidationContext holds configuration and state for a validation run.
func NewValidationContext ¶
func NewValidationContext() *ValidationContext
NewValidationContext creates a new ValidationContext with default settings.
func (*ValidationContext) AddError ¶
func (ctx *ValidationContext) AddError(err ValidationError)
AddError adds an error to the context's collector.
func (*ValidationContext) Collector ¶
func (ctx *ValidationContext) Collector() *ErrorCollector
Collector returns the error collector.
func (*ValidationContext) Context ¶ added in v0.4.0
func (ctx *ValidationContext) Context() context.Context
Context returns the context associated with the current validation run. Custom validators should use it for cancellation/deadline-aware work.
func (*ValidationContext) ContextErr ¶ added in v0.4.0
func (ctx *ValidationContext) ContextErr() error
ContextErr reports context cancellation/deadline failure for this run.
func (*ValidationContext) IsStopped ¶
func (ctx *ValidationContext) IsStopped() bool
IsStopped returns true if validation has been stopped by validation policy or by context cancellation/deadline.
type ValidationError ¶
type ValidationError struct {
Level ErrorLevel
Code string // Stable machine-readable diagnostic code when available.
SchemaPath string // Schema location that produced the diagnostic, when available.
Path string // Stable display path, e.g. "spec.containers[0].image".
PathTokens []PathToken // Typed path components for programmatic consumers.
Line int // 1-based line number (0 if unknown)
Column int // 1-based column number (0 if unknown)
Message string
Got string // Actual value/type description
Expected string // Expected value/type description
Details any // Optional typed machine-readable diagnostic details.
}
ValidationError represents a single validation issue.
func (ValidationError) Error ¶
func (e ValidationError) Error() string
type ValidationResult ¶
type ValidationResult struct {
// Collector contains all errors and warnings.
Collector *ErrorCollector
// SourceLines contains the original YAML lines.
SourceLines []string
// Truncated reports that validation stopped because MaxDiagnostics was reached.
Truncated bool
// Canceled reports that validation stopped because its context was canceled
// or its deadline expired. Context-aware methods also return ContextErr.
Canceled bool
// ContextErr is context.Canceled or context.DeadlineExceeded when Canceled is true.
ContextErr error
}
ValidationResult contains the validation outcome and context for formatting.
func (*ValidationResult) FormatAll ¶
func (r *ValidationResult) FormatAll(sortByPos bool) string
FormatAll formats all errors with source context.
func (*ValidationResult) HasErrors ¶
func (r *ValidationResult) HasErrors() bool
HasErrors returns true if there are any errors.
func (*ValidationResult) SortByPosition ¶
func (r *ValidationResult) SortByPosition()
SortByPosition sorts errors by position in the file.
type Validator ¶
type Validator struct {
// contains filtered or unexported fields
}
Validator performs YAML validation against a schema.
func CompileFieldSchema ¶ added in v0.3.0
func CompileFieldSchema(schema *FieldSchema) (*Validator, error)
CompileFieldSchema validates a native FieldSchema before constructing a Validator. New code should prefer this over NewValidator when schemas are assembled dynamically or loaded from configuration.
func NewValidator ¶
func NewValidator(schema *FieldSchema) *Validator
NewValidator creates a Validator that references the supplied schema directly. Callers must not mutate that schema concurrently with validation. Prefer CompileFieldSchema when an immutable, concurrency-safe schema snapshot is desired.
func (*Validator) ValidateBytes ¶
func (v *Validator) ValidateBytes(data []byte) *ValidationResult
ValidateBytes validates YAML data and returns the result. Supports multi-document YAML (separated by ---).
func (*Validator) ValidateContext ¶ added in v0.4.0
ValidateContext validates YAML data with cancellation/deadline support. Validation diagnostics remain in the returned result; the error is reserved for context cancellation/deadline.
func (*Validator) ValidateContextWithOptions ¶ added in v0.4.0
func (v *Validator) ValidateContextWithOptions( runCtx context.Context, data []byte, opts ValidationContext, ) (*ValidationResult, error)
ValidateContextWithOptions is the context-aware form of ValidateWithOptions.
func (*Validator) ValidateReader ¶ added in v0.5.0
func (v *Validator) ValidateReader(reader io.Reader) (*ValidationResult, error)
ValidateReader validates YAML read from reader. Validation failures are returned in ValidationResult; the error is reserved for input I/O failures.
func (*Validator) ValidateReaderContext ¶ added in v0.5.0
func (v *Validator) ValidateReaderContext( runCtx context.Context, reader io.Reader, ) (*ValidationResult, error)
ValidateReaderContext validates YAML from reader with cancellation/deadline support.
func (*Validator) ValidateReaderContextWithOptions ¶ added in v0.5.0
func (v *Validator) ValidateReaderContextWithOptions( runCtx context.Context, reader io.Reader, opts ValidationContext, ) (*ValidationResult, error)
ValidateReaderContextWithOptions reads at most MaxBytes+1 bytes when a byte limit is configured, so oversized streams are rejected without unbounded buffering. Validation still preserves source lines for normal diagnostics.
func (*Validator) ValidateReaderWithOptions ¶ added in v0.5.0
func (v *Validator) ValidateReaderWithOptions( reader io.Reader, opts ValidationContext, ) (*ValidationResult, error)
ValidateReaderWithOptions is the reader-based form of ValidateWithOptions.
func (*Validator) ValidateWithOptions ¶
func (v *Validator) ValidateWithOptions(data []byte, opts ValidationContext) *ValidationResult
ValidateWithOptions validates YAML data with custom options.
type ValueValidator ¶
type ValueValidator interface {
Validate(node *yaml.Node, path string, ctx *ValidationContext)
}
ValueValidator validates a node's value. Validator instances may be reused concurrently; custom implementations that keep mutable state must therefore provide their own synchronization.
type ValueValidatorCloner ¶ added in v0.4.0
type ValueValidatorCloner interface {
CloneValueValidator() ValueValidator
}
ValueValidatorCloner can be implemented by stateful/configurable custom validators so CompileFieldSchema can snapshot their configuration.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
yamlvalidator
command
|
|
|
examples
|
|
|
advanced
command
|
|
|
basic
command
Example demonstrates how to use the yamlvalidator package to validate Kubernetes-like manifests with comprehensive schema definitions.
|
Example demonstrates how to use the yamlvalidator package to validate Kubernetes-like manifests with comprehensive schema definitions. |
|
internal
|
|
|
thirdparty/xnet/idna
Package idna implements IDNA2008 using the compatibility processing defined by UTS (Unicode Technical Standard) #46, which defines a standard to deal with the transition from IDNA2003.
|
Package idna implements IDNA2008 using the compatibility processing defined by UTS (Unicode Technical Standard) #46, which defines a standard to deal with the transition from IDNA2003. |
|
thirdparty/xtext/secure/bidirule
Package bidirule implements the Bidi Rule defined by RFC 5893.
|
Package bidirule implements the Bidi Rule defined by RFC 5893. |
|
thirdparty/xtext/transform
Package transform provides reader and writer wrappers that transform the bytes passing through as well as various transformations.
|
Package transform provides reader and writer wrappers that transform the bytes passing through as well as various transformations. |
|
thirdparty/xtext/unicode/bidi
Package bidi contains functionality for bidirectional text support.
|
Package bidi contains functionality for bidirectional text support. |
|
thirdparty/xtext/unicode/norm
Package norm contains types and functions for normalizing Unicode strings.
|
Package norm contains types and functions for normalizing Unicode strings. |
|
pkg
|
|