Documentation ¶
Index ¶
- Constants
- Variables
- func CastUint64(v uint64, typ reflect.Type) (reflect.Value, error)
- func ErrUnsupportedHeadPositionType(node ast.Node) error
- func FormatError(e error, colored, inclSource bool) string
- func IsInvalidAliasNameError(err error) bool
- func IsInvalidAnchorNameError(err error) bool
- func IsInvalidPathError(err error) bool
- func IsInvalidPathStringError(err error) bool
- func IsInvalidQueryError(err error) bool
- func IsInvalidTokenTypeError(err error) bool
- func IsNotFoundNodeError(err error) bool
- func JSONToYAML(bytes []byte) ([]byte, error)
- func Marshal(v interface{}) ([]byte, error)
- func MarshalContext(ctx context.Context, v interface{}, opts ...EncodeOption) ([]byte, error)
- func MarshalWithOptions(v interface{}, opts ...EncodeOption) ([]byte, error)
- func NodeToValue(node ast.Node, v interface{}, opts ...DecodeOption) error
- func Unmarshal(data []byte, v interface{}) error
- func UnmarshalContext(ctx context.Context, data []byte, v interface{}, opts ...DecodeOption) error
- func UnmarshalWithOptions(data []byte, v interface{}, opts ...DecodeOption) error
- func ValueToNode(v interface{}, opts ...EncodeOption) (ast.Node, error)
- func YAMLToJSON(bytes []byte) ([]byte, error)
- type BytesMarshaler
- type BytesMarshalerContext
- type BytesUnmarshaler
- type BytesUnmarshalerContext
- type Comment
- type CommentMap
- type CommentPosition
- type DecodeOption
- func DisallowDuplicateKey() DecodeOption
- func DisallowUnknownField() DecodeOption
- func LabelDecoder(label string, f DecoderFn) DecodeOption
- func RecursiveDir(isRecursive bool) DecodeOption
- func ReferenceDirs(dirs ...string) DecodeOption
- func ReferenceFiles(files ...string) DecodeOption
- func ReferenceReaders(readers ...io.Reader) DecodeOption
- func Strict() DecodeOption
- func TypeDecoder(typ reflect.Type, f DecoderFn) DecodeOption
- func UseJSONUnmarshaler() DecodeOption
- func UseOrderedMap() DecodeOption
- func Validator(v StructValidator) DecodeOption
- type Decoder
- type DecoderFn
- type EncodeOption
- func Flow(isFlowStyle bool) EncodeOption
- func Indent(spaces int) EncodeOption
- func IndentSequence(indent bool) EncodeOption
- func JSON() EncodeOption
- func KeyNaming(v KeyNamingStrategy) EncodeOption
- func MarshalAnchor(callback func(*ast.AnchorNode, interface{}) error) EncodeOption
- func UseJSONMarshaler() EncodeOption
- func UseLiteralStyleIfMultiline(useLiteralStyleIfMultiline bool) EncodeOption
- func WithComment(cm CommentMap) EncodeOption
- type Encoder
- func (e *Encoder) Close() error
- func (e *Encoder) Encode(v interface{}) error
- func (e *Encoder) EncodeContext(ctx context.Context, v interface{}) error
- func (e *Encoder) EncodeToNode(v interface{}) (ast.Node, error)
- func (e *Encoder) EncodeToNodeContext(ctx context.Context, v interface{}) (ast.Node, error)
- type FieldError
- type InterfaceMarshaler
- type InterfaceMarshalerContext
- type InterfaceUnmarshaler
- type InterfaceUnmarshalerContext
- type IsZeroer
- type KeyNamingStrategy
- type MapItem
- type MapSlice
- type Path
- func (p *Path) AnnotateSource(source []byte, colored bool) ([]byte, error)
- func (p *Path) Filter(target, v interface{}) error
- func (p *Path) FilterFile(f *ast.File) (ast.Node, error)
- func (p *Path) FilterNode(node ast.Node) (ast.Node, error)
- func (p *Path) MergeFromFile(dst *ast.File, src *ast.File) error
- func (p *Path) MergeFromNode(dst *ast.File, src ast.Node) error
- func (p *Path) MergeFromReader(dst *ast.File, src io.Reader) error
- func (p *Path) Read(r io.Reader, v interface{}) error
- func (p *Path) ReadNode(r io.Reader) (ast.Node, error)
- func (p *Path) ReplaceWithFile(dst *ast.File, src *ast.File) error
- func (p *Path) ReplaceWithNode(dst *ast.File, node ast.Node) error
- func (p *Path) ReplaceWithReader(dst *ast.File, src io.Reader) error
- func (p *Path) String() string
- type PathBuilder
- type StructField
- type StructFieldMap
- type StructValidator
Examples ¶
Constants ¶
const (
// DefaultIndentSpaces default number of space for indent
DefaultIndentSpaces = 2
)
Variables ¶
var ( ErrInvalidQuery = xerrors.New("invalid query") ErrInvalidPath = xerrors.New("invalid path instance") ErrInvalidPathString = xerrors.New("invalid path string") ErrNotFoundNode = xerrors.New("node not found") ErrUnknownCommentPositionType = xerrors.New("unknown comment position type") )
var ErrContinue = xerrors.New("continue processing")
Functions ¶
func CastUint64 ¶
CastUint64 casts an uint64 to target typ.
func FormatError ¶
FormatError is a utility function that takes advantage of the metadata stored in the errors returned by this package's parser.
If the second argument `colored` is true, the error message is colorized. If the third argument `inclSource` is true, the error message will contain snippets of the YAML source that was used.
func IsInvalidAliasNameError ¶
IsInvalidAliasNameError whether err is ast.ErrInvalidAliasName or not.
func IsInvalidAnchorNameError ¶
IsInvalidAnchorNameError whether err is ast.ErrInvalidAnchorName or not.
func IsInvalidPathError ¶
IsInvalidPathError whether err is ErrInvalidPath or not.
func IsInvalidPathStringError ¶
IsInvalidPathStringError whether err is ErrInvalidPathString or not.
func IsInvalidQueryError ¶
IsInvalidQueryError whether err is ErrInvalidQuery or not.
func IsInvalidTokenTypeError ¶
IsInvalidTokenTypeError whether err is ast.ErrInvalidTokenType or not.
func IsNotFoundNodeError ¶
IsNotFoundNodeError whether err is ErrNotFoundNode or not.
func JSONToYAML ¶
JSONToYAML convert JSON bytes to YAML.
func Marshal ¶
Marshal serializes the value provided into a YAML document. The structure of the generated document will reflect the structure of the value itself. Maps and pointers (to struct, string, int, etc) are accepted as the in value.
Struct fields are only marshalled if they are exported (have an upper case first letter), and are marshalled using the field name lowercased as the default key. Custom keys may be defined via the "yaml" name in the field tag: the content preceding the first comma is used as the key, and the following comma-separated options are used to tweak the marshalling process. Conflicting names result in a runtime error.
The field tag format accepted is:
`(...) yaml:"[<key>][,<flag1>[,<flag2>]]" (...)`
The following flags are currently supported:
omitempty Only include the field if it's not set to the zero value for the type or to empty slices or maps. Zero valued structs will be omitted if all their public fields are zero, unless they implement an IsZero method (see the IsZeroer interface type), in which case the field will be included if that method returns true. flow Marshal using a flow style (useful for structs, sequences and maps). inline Inline the field, which must be a struct or a map, causing all of its fields or keys to be processed as if they were part of the outer struct. For maps, keys must not conflict with the yaml keys of other struct fields. anchor Marshal with anchor. If want to define anchor name explicitly, use anchor=name style. Otherwise, if used 'anchor' name only, used the field name lowercased as the anchor name alias Marshal with alias. If want to define alias name explicitly, use alias=name style. Otherwise, If omitted alias name and the field type is pointer type, assigned anchor name automatically from same pointer address.
In addition, if the key is "-", the field is ignored.
For example:
type T struct { F int `yaml:"a,omitempty"` B int } yaml.Marshal(&T{B: 2}) // Returns "b: 2\n" yaml.Marshal(&T{F: 1}) // Returns "a: 1\nb: 0\n"
func MarshalContext ¶
func MarshalContext(ctx context.Context, v interface{}, opts ...EncodeOption) ([]byte, error)
MarshalContext serializes the value provided into a YAML document with context.Context and EncodeOptions.
func MarshalWithOptions ¶
func MarshalWithOptions(v interface{}, opts ...EncodeOption) ([]byte, error)
MarshalWithOptions serializes the value provided into a YAML document with EncodeOptions.
func NodeToValue ¶
func NodeToValue(node ast.Node, v interface{}, opts ...DecodeOption) error
NodeToValue converts node to the value pointed to by v.
func Unmarshal ¶
Unmarshal decodes the first document found within the in byte slice and assigns decoded values into the out value.
Struct fields are only unmarshalled if they are exported (have an upper case first letter), and are unmarshalled using the field name lowercased as the default key. Custom keys may be defined via the "yaml" name in the field tag: the content preceding the first comma is used as the key, and the following comma-separated options are used to tweak the marshalling process (see Marshal). Conflicting names result in a runtime error.
For example:
type T struct { F int `yaml:"a,omitempty"` B int } var t T yaml.Unmarshal([]byte("a: 1\nb: 2"), &t)
See the documentation of Marshal for the format of tags and a list of supported tag options.
func UnmarshalContext ¶
func UnmarshalContext(ctx context.Context, data []byte, v interface{}, opts ...DecodeOption) error
UnmarshalContext decodes with context.Context and DecodeOptions.
func UnmarshalWithOptions ¶
func UnmarshalWithOptions(data []byte, v interface{}, opts ...DecodeOption) error
UnmarshalWithOptions decodes with DecodeOptions the first document found within the in byte slice and assigns decoded values into the out value.
func ValueToNode ¶
func ValueToNode(v interface{}, opts ...EncodeOption) (ast.Node, error)
ValueToNode convert from value to ast.Node.
func YAMLToJSON ¶
YAMLToJSON convert YAML bytes to JSON.
Types ¶
type BytesMarshaler ¶
BytesMarshaler interface may be implemented by types to customize their behavior when being marshaled into a YAML document. The returned value is marshaled in place of the original value implementing Marshaler.
If an error is returned by MarshalYAML, the marshaling procedure stops and returns with the provided error.
type BytesMarshalerContext ¶
BytesMarshalerContext interface use BytesMarshaler with context.Context.
type BytesUnmarshaler ¶
BytesUnmarshaler interface may be implemented by types to customize their behavior when being unmarshaled from a YAML document.
type BytesUnmarshalerContext ¶
BytesUnmarshalerContext interface use BytesUnmarshaler with context.Context.
type Comment ¶
type Comment struct { Texts []string Position CommentPosition }
Comment raw data for comment.
func HeadComment ¶
HeadComment create a multiline comment for CommentMap.
func LineComment ¶
LineComment create a one-line comment for CommentMap.
type CommentMap ¶
CommentMap map of the position of the comment and the comment information.
type CommentPosition ¶
type CommentPosition int
CommentPosition type of the position for comment.
const ( CommentLinePosition CommentPosition = iota CommentHeadPosition )
func (CommentPosition) String ¶
func (p CommentPosition) String() string
type DecodeOption ¶
DecodeOption functional option type for Decoder
func DisallowDuplicateKey ¶
func DisallowDuplicateKey() DecodeOption
DisallowDuplicateKey causes an error when mapping keys that are duplicates
func DisallowUnknownField ¶
func DisallowUnknownField() DecodeOption
DisallowUnknownField causes the Decoder to return an error when the destination is a struct and the input contains object keys which do not match any non-ignored, exported fields in the destination.
func LabelDecoder ¶
func LabelDecoder(label string, f DecoderFn) DecodeOption
LabelDecoder registers a decoder associated with a label defined in the struct tag like 'yaml:"name,label=xyz".
func RecursiveDir ¶
func RecursiveDir(isRecursive bool) DecodeOption
RecursiveDir search yaml file recursively from passed dirs by ReferenceDirs option
func ReferenceDirs ¶
func ReferenceDirs(dirs ...string) DecodeOption
ReferenceDirs pass to Decoder that reference to anchor defined by files under the passed dirs
func ReferenceFiles ¶
func ReferenceFiles(files ...string) DecodeOption
ReferenceFiles pass to Decoder that reference to anchor defined by passed files
func ReferenceReaders ¶
func ReferenceReaders(readers ...io.Reader) DecodeOption
ReferenceReaders pass to Decoder that reference to anchor defined by passed readers
func Strict ¶
func Strict() DecodeOption
Strict enable DisallowUnknownField and DisallowDuplicateKey
func TypeDecoder ¶
func TypeDecoder(typ reflect.Type, f DecoderFn) DecodeOption
TypeDecoder registers a decoder associated with a struct field type.
func UseJSONUnmarshaler ¶
func UseJSONUnmarshaler() DecodeOption
UseJSONUnmarshaler if neither `BytesUnmarshaler` nor `InterfaceUnmarshaler` is implemented and `UnmashalJSON([]byte)error` is implemented, convert the argument from `YAML` to `JSON` and then call it.
func UseOrderedMap ¶
func UseOrderedMap() DecodeOption
UseOrderedMap can be interpreted as a map, and uses MapSlice ( ordered map ) aggressively if there is no type specification
func Validator ¶
func Validator(v StructValidator) DecodeOption
Validator set StructValidator instance to Decoder
type Decoder ¶
type Decoder struct {
// contains filtered or unexported fields
}
Decoder reads and decodes YAML values from an input stream.
func NewDecoder ¶
func NewDecoder(r io.Reader, opts ...DecodeOption) *Decoder
NewDecoder returns a new decoder that reads from r.
func (*Decoder) Decode ¶
Decode reads the next YAML-encoded value from its input and stores it in the value pointed to by v.
See the documentation for Unmarshal for details about the conversion of YAML into a Go value.
func (*Decoder) DecodeContext ¶
DecodeContext reads the next YAML-encoded value from its input and stores it in the value pointed to by v with context.Context.
func (*Decoder) DecodeFromNode ¶
DecodeFromNode decodes node into the value pointed to by v.
type DecoderFn ¶
DecoderFn is a prototype func for customized decoding of yaml values. If err returns ErrContinue, the decoding will continued after the func invoking.
type EncodeOption ¶
EncodeOption functional option type for Encoder
func IndentSequence ¶
func IndentSequence(indent bool) EncodeOption
IndentSequence causes sequence values to be indented the same value as Indent
func KeyNaming ¶
func KeyNaming(v KeyNamingStrategy) EncodeOption
KeyNaming changes the yaml keys' naming when encoding structs.
func MarshalAnchor ¶
func MarshalAnchor(callback func(*ast.AnchorNode, interface{}) error) EncodeOption
MarshalAnchor call back if encoder find an anchor during encoding
func UseJSONMarshaler ¶
func UseJSONMarshaler() EncodeOption
UseJSONMarshaler if neither `BytesMarshaler` nor `InterfaceMarshaler` nor `encoding.TextMarshaler` is implemented and `MarshalJSON()([]byte, error)` is implemented, call `MarshalJSON` to convert the returned `JSON` to `YAML` for processing.
func UseLiteralStyleIfMultiline ¶
func UseLiteralStyleIfMultiline(useLiteralStyleIfMultiline bool) EncodeOption
UseLiteralStyleIfMultiline causes encoding multiline strings with a literal syntax, no matter what characters they include
func WithComment ¶
func WithComment(cm CommentMap) EncodeOption
WithComment add a comment using the location and text information given in the CommentMap.
type Encoder ¶
type Encoder struct { KeyNaming KeyNamingStrategy // contains filtered or unexported fields }
Encoder writes YAML values to an output stream.
func NewEncoder ¶
func NewEncoder(w io.Writer, opts ...EncodeOption) *Encoder
NewEncoder returns a new encoder that writes to w. The Encoder should be closed after use to flush all data to w.
func (*Encoder) Close ¶
Close closes the encoder by writing any remaining data. It does not write a stream terminating string "...".
func (*Encoder) Encode ¶
Encode writes the YAML encoding of v to the stream. If multiple items are encoded to the stream, the second and subsequent document will be preceded with a "---" document separator, but the first will not.
See the documentation for Marshal for details about the conversion of Go values to YAML.
func (*Encoder) EncodeContext ¶
EncodeContext writes the YAML encoding of v to the stream with context.Context.
func (*Encoder) EncodeToNode ¶
EncodeToNode convert v to ast.Node.
type FieldError ¶
type FieldError interface {
StructField() string
}
FieldError need to implement StructField method only ( see https://pkg.go.dev/github.com/go-playground/validator/v10#FieldError )
type InterfaceMarshaler ¶
type InterfaceMarshaler interface {
MarshalYAML() (interface{}, error)
}
InterfaceMarshaler interface has MarshalYAML compatible with github.com/go-yaml/yaml package.
type InterfaceMarshalerContext ¶
InterfaceMarshalerContext interface use InterfaceMarshaler with context.Context.
type InterfaceUnmarshaler ¶
InterfaceUnmarshaler interface has UnmarshalYAML compatible with github.com/go-yaml/yaml package.
type InterfaceUnmarshalerContext ¶
type InterfaceUnmarshalerContext interface {
UnmarshalYAML(context.Context, func(interface{}) error) error
}
InterfaceUnmarshalerContext interface use InterfaceUnmarshaler with context.Context.
type IsZeroer ¶
type IsZeroer interface {
IsZero() bool
}
IsZeroer is used to check whether an object is zero to determine whether it should be omitted when marshaling with the omitempty flag. One notable implementation is time.Time.
type KeyNamingStrategy ¶
type KeyNamingStrategy int
const ( KeyNamingDefault KeyNamingStrategy = iota KeyNamingRaw KeyNamingLowerCamel )
type MapSlice ¶
type MapSlice []MapItem
MapSlice encodes and decodes as a YAML map. The order of keys is preserved when encoding and decoding.
type Path ¶
type Path struct {
// contains filtered or unexported fields
}
Path represent YAMLPath ( like a JSONPath ).
func PathString ¶
PathString create Path from string
YAMLPath rule $ : the root object/element . : child operator .. : recursive descent [num] : object/element of array by number [*] : all objects/elements for array.
func (*Path) AnnotateSource ¶
AnnotateSource add annotation to passed source ( see section 5.1 in README.md ).
Example ¶
package main import ( "fmt" "log" "github.com/bingoohuang/gg/pkg/yaml" ) func main() { yml := ` a: 1 b: "hello" ` var v struct { A int B string } if err := yaml.Unmarshal([]byte(yml), &v); err != nil { panic(err) } if v.A != 2 { // output error with YAML source path, err := yaml.PathString("$.a") if err != nil { log.Fatal(err) } source, err := path.AnnotateSource([]byte(yml), false) if err != nil { log.Fatal(err) } fmt.Printf("a value expected 2 but actual %d:\n%s\n", v.A, string(source)) } }
Output: a value expected 2 but actual 1: > 2 | a: 1 ^ 3 | b: "hello"
func (*Path) FilterFile ¶
FilterFile filter from ast.File by YAMLPath.
func (*Path) FilterNode ¶
FilterNode filter from node by YAMLPath.
func (*Path) MergeFromFile ¶
MergeFromFile merge ast.File into ast.File.
func (*Path) MergeFromNode ¶
MergeFromNode merge ast.Node into ast.File.
func (*Path) MergeFromReader ¶
MergeFromReader merge YAML text into ast.File.
func (*Path) ReplaceWithFile ¶
ReplaceWithFile replace ast.File with ast.File.
func (*Path) ReplaceWithNode ¶
ReplaceNode replace ast.File with ast.Node.
func (*Path) ReplaceWithReader ¶
ReplaceWithReader replace ast.File with io.Reader.
type PathBuilder ¶
type PathBuilder struct {
// contains filtered or unexported fields
}
PathBuilder represent builder for YAMLPath.
func (*PathBuilder) Child ¶
func (b *PathBuilder) Child(name string) *PathBuilder
Child add '.name' to current path.
func (*PathBuilder) Index ¶
func (b *PathBuilder) Index(idx uint) *PathBuilder
Index add '[idx]' to current path.
func (*PathBuilder) IndexAll ¶
func (b *PathBuilder) IndexAll() *PathBuilder
IndexAll add '[*]' to current path.
func (*PathBuilder) Recursive ¶
func (b *PathBuilder) Recursive(selector string) *PathBuilder
Recursive add '..selector' to current path.
type StructField ¶
type StructField struct { FieldName string RenderName string AnchorName string AliasName string Label string IsAutoAnchor bool IsAutoAlias bool IsOmitEmpty bool IsFlow bool IsInline bool RenderNameFromTag bool }
StructField information for each the field in structure
type StructFieldMap ¶
type StructFieldMap map[string]*StructField
type StructValidator ¶
type StructValidator interface {
Struct(interface{}) error
}
StructValidator need to implement Struct method only ( see https://pkg.go.dev/github.com/go-playground/validator/v10#Validate.Struct )