Documentation
¶
Overview ¶
Package libyaml contains internal helpers for working with YAML
It's a reworked version of the original libyaml package from go-yaml v2/v3, adapted to work with Go specifications
Index ¶
- Constants
- Variables
- func DefaultAliasCheck(aliasCount, constructCount int) error
- func DefaultDepthCheck(depth int, ctx *DepthContext) error
- func Dump(in any, opts ...Option) (out []byte, err error)
- func Fail(err error)
- func Load(in []byte, out any, opts ...Option) error
- func LoadAny(data []byte) (any, error)
- func ParserGetEvents(in []byte) (string, error)
- type AliasData
- type Comment
- type Composer
- type Constructor
- type DepthContext
- type DepthKind
- type Desolver
- type DumpError
- type Dumper
- type Emitter
- func (emitter *Emitter) Delete()
- func (emitter *Emitter) Emit(event *Event) error
- func (emitter *Emitter) SetCanonical(canonical bool)
- func (emitter *Emitter) SetEncoding(encoding Encoding)
- func (emitter *Emitter) SetIndent(indent int)
- func (emitter *Emitter) SetLineBreak(line_break LineBreak)
- func (emitter *Emitter) SetOutputString(output_buffer *[]byte)
- func (emitter *Emitter) SetOutputWriter(w io.Writer)
- func (emitter *Emitter) SetUnicode(unicode bool)
- func (emitter *Emitter) SetWidth(width int)
- type EmitterError
- type EmitterState
- type Encoding
- type ErrorType
- type Event
- func NewAliasEvent(anchor []byte) Event
- func NewDocumentEndEvent(implicit bool) Event
- func NewDocumentStartEvent(version_directive *VersionDirective, tag_directives []TagDirective, ...) Event
- func NewMappingEndEvent() Event
- func NewMappingStartEvent(anchor, tag []byte, implicit bool, style MappingStyle) Event
- func NewScalarEvent(anchor, tag, value []byte, plain_implicit, quoted_implicit bool, ...) Event
- func NewSequenceEndEvent() Event
- func NewSequenceStartEvent(anchor, tag []byte, implicit bool, style SequenceStyle) Event
- func NewStreamEndEvent() Event
- func NewStreamStartEvent(encoding Encoding) Event
- func (e *Event) Delete()
- func (e *Event) GetEncoding() Encoding
- func (e *Event) GetTagDirectives() []TagDirective
- func (e *Event) GetVersionDirective() *VersionDirective
- func (e *Event) MappingStyle() MappingStyle
- func (e *Event) ScalarStyle() ScalarStyle
- func (e *Event) SequenceStyle() SequenceStyle
- type EventType
- type FromYAMLNode
- type IsZeroer
- type Kind
- type LineBreak
- type LoadError
- type LoadErrors
- type Loader
- type MappingStyle
- type Mark
- type Marshaler
- type Node
- func (n *Node) Decode(v any) (err error)
- func (n *Node) Dump(v any, opts ...Option) (err error)
- func (n *Node) Encode(v any) (err error)
- func (n *Node) IsZero() bool
- func (n *Node) Load(v any, opts ...Option) (err error)
- func (n *Node) LongTag() string
- func (n *Node) SetString(s string)
- func (n *Node) ShortTag() string
- type Option
- func CombineOptions(opts ...Option) Option
- func WithAllDocuments(all ...bool) Option
- func WithCanonical(canonical ...bool) Option
- func WithCompactSeqIndent(compact ...bool) Option
- func WithExplicitEnd(explicit ...bool) Option
- func WithExplicitStart(explicit ...bool) Option
- func WithFlowSimpleCollections(flow ...bool) Option
- func WithIndent(indent int) Option
- func WithKnownFields(knownFields ...bool) Option
- func WithLineBreak(lineBreak LineBreak) Option
- func WithLineWidth(width int) Option
- func WithQuotePreference(style QuoteStyle) Option
- func WithSingleDocument(singleDocument ...bool) Option
- func WithStreamNodes(enable ...bool) Option
- func WithUnicode(unicode ...bool) Option
- func WithUniqueKeys(uniqueKeys ...bool) Option
- type Options
- type Parser
- func (parser *Parser) Delete()
- func (parser *Parser) GetCommentsHead() int
- func (parser *Parser) GetPendingComments() []Comment
- func (parser *Parser) Parse(event *Event) error
- func (parser *Parser) Scan(token *Token) error
- func (parser *Parser) SetEncoding(encoding Encoding)
- func (parser *Parser) SetInputReader(r io.Reader)
- func (parser *Parser) SetInputString(input []byte)
- func (parser *Parser) SetSkipComments(skip bool)
- func (parser *Parser) UnfoldComments(token *Token)
- type ParserState
- type QuoteStyle
- type ReadHandler
- type Representer
- type Resolver
- type ScalarConstructFunc
- type ScalarStyle
- type SequenceStyle
- type Serializer
- type SimpleKey
- type Stage
- type Stream
- type StreamTagDirective
- type StreamVersionDirective
- type Style
- type TagDirective
- type ToYAMLNode
- type Token
- type TokenType
- type TypeErrordeprecated
- type Unmarshaler
- type VersionDirective
- type WriteHandler
- type WriterError
- type YAMLError
Constants ¶
const ( NULL_TAG = "tag:yaml.org,2002:null" // The tag !!null with the only possible value: null. BOOL_TAG = "tag:yaml.org,2002:bool" // The tag !!bool with the values: true and false. STR_TAG = "tag:yaml.org,2002:str" // The tag !!str for string values. INT_TAG = "tag:yaml.org,2002:int" // The tag !!int for integer values. FLOAT_TAG = "tag:yaml.org,2002:float" // The tag !!float for float values. TIMESTAMP_TAG = "tag:yaml.org,2002:timestamp" // The tag !!timestamp for date and time values. SEQ_TAG = "tag:yaml.org,2002:seq" // The tag !!seq is used to denote sequences. MAP_TAG = "tag:yaml.org,2002:map" // The tag !!map is used to denote mapping. // Not in original libyaml. BINARY_TAG = "tag:yaml.org,2002:binary" MERGE_TAG = "tag:yaml.org,2002:merge" DEFAULT_SCALAR_TAG = STR_TAG // The default scalar tag is !!str. DEFAULT_SEQUENCE_TAG = SEQ_TAG // The default sequence tag is !!seq. DEFAULT_MAPPING_TAG = MAP_TAG // The default mapping tag is !!map. )
Nodes
Variables ¶
var DefaultOptions = &Options{ Indent: 4, LineWidth: -1, Unicode: true, UniqueKeys: true, QuotePreference: QuoteLegacy, }
DefaultOptions holds the default options for APIs that don't accept options.
Functions ¶
func DefaultAliasCheck ¶
DefaultAliasCheck is the default alias check function. It uses a ratio-based heuristic to prevent DoS attacks via excessive aliasing.
func DefaultDepthCheck ¶
func DefaultDepthCheck(depth int, ctx *DepthContext) error
DefaultDepthCheck is the default depth check function. It returns an error when depth exceeds 10000.
func Dump ¶
Dump encodes a value to YAML with the given options.
By default, Dump encodes a single value as a single YAML document.
Use WithAllDocuments() to encode multiple values as a multi-document stream:
docs := []Config{config1, config2, config3}
yaml.Dump(docs, yaml.WithAllDocuments())
When WithAllDocuments is used, in must be a slice. Each element is encoded as a separate YAML document with "---" separators.
See [Marshal] for details about the conversion of Go values to YAML.
func Load ¶
Load loads YAML document(s) with the given options.
By default, Load requires exactly one document in the input. If zero documents are found, it returns an error. If multiple documents are found, it returns an error.
Use WithAllDocuments() to load all documents into a slice:
var configs []Config yaml.Load(multiDocYAML, &configs, yaml.WithAllDocuments())
When WithAllDocuments is used, out must be a pointer to a slice. Each document is loaded into the slice element type. Zero documents results in an empty slice (no error).
Maps and pointers (to a struct, string, int, etc) are accepted as out values. If an internal pointer within a struct is not initialized, the yaml package will initialize it if necessary. The out parameter must not be nil.
The type of the loaded values should be compatible with the respective values in out. If one or more values cannot be loaded due to type mismatches, decoding continues partially until the end of the YAML content, and a *yaml.LoadErrors is returned with details for all missed values.
Struct fields are only loaded if they are exported (have an upper case first letter), and are loaded 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 control the loading and dumping behavior.
For example:
type T struct {
F int `yaml:"a,omitempty"`
B int
}
var t T
yaml.Load([]byte("a: 1\nb: 2"), &t)
See the documentation of Dump for the format of tags and a list of supported tag options.
func LoadAny ¶
LoadAny parses YAML data into generic Go structures (map[string]any, []any).
Useful for test data loading where the structure is unknown at compile time. This is a convenience wrapper around Load with an any target.
func ParserGetEvents ¶
ParserGetEvents parses the YAML input and returns the generated event stream.
Types ¶
type AliasData ¶
type AliasData struct {
// contains filtered or unexported fields
}
AliasData holds information about aliases.
type Comment ¶
type Comment struct {
ScanMark Mark // Position where scanning for comments started
TokenMark Mark // Position after which tokens will be associated with this comment
StartMark Mark // Position of '#' comment mark
EndMark Mark // Position where comment terminated
Head []byte
Line []byte
Foot []byte
}
Comment holds information about a comment in the YAML stream.
type Composer ¶
Composer produces a node tree out of a libyaml event stream.
func NewComposer ¶
NewComposer creates a new composer from a byte slice.
func NewComposerFromReader ¶
NewComposerFromReader creates a new composer from an io.Reader.
func (*Composer) Destroy ¶
func (c *Composer) Destroy()
Destroy cleans up the composer by deleting any pending event and the underlying parser.
func (*Composer) SetStreamNodes ¶
SetStreamNodes enables or disables stream node emission.
type Constructor ¶
type Constructor struct {
TypeErrors []*LoadError
KnownFields bool
UniqueKeys bool
// contains filtered or unexported fields
}
Constructor state
func NewConstructor ¶
func NewConstructor(opts *Options) *Constructor
NewConstructor creates a new Constructor initialized with the provided options.
func (*Constructor) Construct ¶
func (c *Constructor) Construct(n *Node, out reflect.Value) (good bool)
Construct converts a YAML node into the Go value represented by out. It dispatches to the appropriate handler based on the node kind and handles alias expansion, custom unmarshalers, and type resolution. Returns true if the construction was successful.
type DepthContext ¶
type DepthContext struct {
Kind DepthKind
}
DepthContext holds context about a nesting depth check.
type Desolver ¶
type Desolver struct {
// contains filtered or unexported fields
}
Desolver handles tag removal for YAML nodes during serialization. It removes tags that would be automatically resolved to the same type during parsing, making the output cleaner and more readable.
func NewDesolver ¶
NewDesolver creates a new Desolver with the given options.
func (*Desolver) Desolve ¶
Desolve walks the node tree and removes tags that can be inferred. This is the inverse of Resolver - it takes a fully-tagged node tree (from Representer) and removes unnecessary tags to produce clean output.
For scalar nodes: if the value would resolve to the same tag when parsed, the tag is removed. For strings that would resolve differently, the tag is removed and quoting style is set to preserve the string type.
For collection nodes (maps/sequences): default tags (!!map, !!seq) are removed since they're implied by the structure.
type DumpError ¶
type DumpError struct {
Stage Stage // Processing stage where error occurred
Message string // Error description
// contains filtered or unexported fields
}
DumpError represents an error that occurred while dumping a YAML document.
It identifies the processing stage where the error occurred and provides an optional underlying cause via Unwrap.
func NewDumpError ¶
NewDumpError creates a DumpError with an underlying cause. The cause is accessible via Unwrap for use with errors.Is and errors.As.
type Dumper ¶
type Dumper struct {
// contains filtered or unexported fields
}
A Dumper writes YAML values to an output stream with configurable options. It uses a 3-stage pipeline mirroring the Loader:
- Representer: Go values → Tagged Node tree
- Desolver: Remove inferable tags
- Serializer: Node tree → Events → YAML
func NewDumper ¶
NewDumper returns a new Dumper that writes to w with the given options.
The Dumper should be closed after use to flush all data to w.
func (*Dumper) Close ¶
Close closes the Dumper by writing any remaining data. It does not write a stream terminating string "...".
func (*Dumper) Dump ¶
Dump writes the YAML encoding of v to the stream.
If multiple values are dumped to the stream, the second and subsequent documents will be preceded with a "---" document separator.
See the documentation for [Marshal] for details about the conversion of Go values to YAML.
func (*Dumper) SetCompactSeqIndent ¶
SetCompactSeqIndent controls whether '- ' is considered part of the indentation. This is used by the legacy Encoder methods.
type Emitter ¶
type Emitter struct {
BestIndent int // The number of indentation spaces.
CompactSequenceIndent bool // Is '- ' is considered part of the indentation for sequence elements?
OpenEnded bool // If an explicit document end is required?
// Comments
HeadComment []byte
LineComment []byte
FootComment []byte
TailComment []byte
// contains filtered or unexported fields
}
Emitter holds all information about the current state of the emitter.
func (*Emitter) SetCanonical ¶
SetCanonical sets the canonical output style.
func (*Emitter) SetEncoding ¶
SetEncoding sets the output encoding.
func (*Emitter) SetLineBreak ¶
SetLineBreak sets the preferred line break character.
func (*Emitter) SetOutputString ¶
SetOutputString sets a string output.
func (*Emitter) SetOutputWriter ¶
SetOutputWriter sets a file output.
func (*Emitter) SetUnicode ¶
SetUnicode sets if unescaped non-ASCII characters are allowed.
type EmitterError ¶
type EmitterError struct {
Message string
}
EmitterError represents an error that occurred during emitting.
type EmitterState ¶
type EmitterState int
EmitterState represents the current state of the emitter.
const ( // Expect STREAM-START. EMIT_STREAM_START_STATE EmitterState = iota EMIT_FIRST_DOCUMENT_START_STATE // Expect the first DOCUMENT-START or STREAM-END. EMIT_DOCUMENT_START_STATE // Expect DOCUMENT-START or STREAM-END. EMIT_DOCUMENT_CONTENT_STATE // Expect the content of a document. EMIT_DOCUMENT_END_STATE // Expect DOCUMENT-END. EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a flow sequence. EMIT_FLOW_SEQUENCE_TRAIL_ITEM_STATE // Expect the next item of a flow sequence, with the comma already written out EMIT_FLOW_SEQUENCE_ITEM_STATE // Expect an item of a flow sequence. EMIT_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. EMIT_FLOW_MAPPING_TRAIL_KEY_STATE // Expect the next key of a flow mapping, with the comma already written out EMIT_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a flow mapping. EMIT_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a block sequence. EMIT_BLOCK_SEQUENCE_ITEM_STATE // Expect an item of a block sequence. EMIT_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. EMIT_BLOCK_MAPPING_KEY_STATE // Expect the key of a block mapping. EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a block mapping. EMIT_BLOCK_MAPPING_VALUE_STATE // Expect a value of a block mapping. EMIT_END_STATE // Expect nothing. )
The emitter states.
type ErrorType ¶
type ErrorType int
ErrorType represents the category of error that occurred during processing.
const ( // No error is produced. NO_ERROR ErrorType = iota MEMORY_ERROR // Cannot allocate or reallocate a block of memory. READER_ERROR // Cannot read or decode the input stream. SCANNER_ERROR // Cannot scan the input stream. PARSER_ERROR // Cannot parse the input stream. COMPOSER_ERROR // Cannot compose a YAML document. WRITER_ERROR // Cannot write to the output stream. EMITTER_ERROR // Cannot emit a YAML stream. )
Many bad things could happen with the parser and emitter.
type Event ¶
type Event struct {
// The event type.
Type EventType
// The start and end of the event.
StartMark, EndMark Mark
// The comments
HeadComment []byte
LineComment []byte
FootComment []byte
TailComment []byte
// The Anchor (for SCALAR_EVENT, SEQUENCE_START_EVENT, MAPPING_START_EVENT, ALIAS_EVENT).
Anchor []byte
// The Tag (for SCALAR_EVENT, SEQUENCE_START_EVENT, MAPPING_START_EVENT).
Tag []byte
// The scalar Value (for SCALAR_EVENT).
Value []byte
// Is the document start/end indicator Implicit, or the tag optional?
// (for DOCUMENT_START_EVENT, DOCUMENT_END_EVENT, SEQUENCE_START_EVENT, MAPPING_START_EVENT, SCALAR_EVENT).
Implicit bool
// The Style (for SCALAR_EVENT, SEQUENCE_START_EVENT, MAPPING_START_EVENT).
Style Style
// contains filtered or unexported fields
}
Event holds information about a parsing or emitting event.
func NewAliasEvent ¶
NewAliasEvent creates a new ALIAS event.
func NewDocumentEndEvent ¶
NewDocumentEndEvent creates a new DOCUMENT-END event.
func NewDocumentStartEvent ¶
func NewDocumentStartEvent(version_directive *VersionDirective, tag_directives []TagDirective, implicit bool) Event
NewDocumentStartEvent creates a new DOCUMENT-START event.
func NewMappingEndEvent ¶
func NewMappingEndEvent() Event
NewMappingEndEvent creates a new MAPPING-END event.
func NewMappingStartEvent ¶
func NewMappingStartEvent(anchor, tag []byte, implicit bool, style MappingStyle) Event
NewMappingStartEvent creates a new MAPPING-START event.
func NewScalarEvent ¶
func NewScalarEvent(anchor, tag, value []byte, plain_implicit, quoted_implicit bool, style ScalarStyle) Event
NewScalarEvent creates a new SCALAR event.
func NewSequenceEndEvent ¶
func NewSequenceEndEvent() Event
NewSequenceEndEvent creates a new SEQUENCE-END event.
func NewSequenceStartEvent ¶
func NewSequenceStartEvent(anchor, tag []byte, implicit bool, style SequenceStyle) Event
NewSequenceStartEvent creates a new SEQUENCE-START event.
func NewStreamEndEvent ¶
func NewStreamEndEvent() Event
NewStreamEndEvent creates a new STREAM-END event.
func NewStreamStartEvent ¶
NewStreamStartEvent creates a new STREAM-START event.
func (*Event) GetEncoding ¶
GetEncoding returns the stream encoding (for STREAM_START_EVENT).
func (*Event) GetTagDirectives ¶
func (e *Event) GetTagDirectives() []TagDirective
GetTagDirectives returns the tag directives (for DOCUMENT_START_EVENT).
func (*Event) GetVersionDirective ¶
func (e *Event) GetVersionDirective() *VersionDirective
GetVersionDirective returns the version directive (for DOCUMENT_START_EVENT).
func (*Event) MappingStyle ¶
func (e *Event) MappingStyle() MappingStyle
MappingStyle returns the style of a mapping event.
func (*Event) ScalarStyle ¶
func (e *Event) ScalarStyle() ScalarStyle
ScalarStyle returns the style of a scalar event.
func (*Event) SequenceStyle ¶
func (e *Event) SequenceStyle() SequenceStyle
SequenceStyle returns the style of a sequence event.
type EventType ¶
type EventType int8
EventType represents the type of a parsing or emitting event.
const ( // An empty event. NO_EVENT EventType = iota STREAM_START_EVENT // A STREAM-START event. STREAM_END_EVENT // A STREAM-END event. DOCUMENT_START_EVENT // A DOCUMENT-START event. DOCUMENT_END_EVENT // A DOCUMENT-END event. ALIAS_EVENT // An ALIAS event. SCALAR_EVENT // A SCALAR event. SEQUENCE_START_EVENT // A SEQUENCE-START event. SEQUENCE_END_EVENT // A SEQUENCE-END event. MAPPING_START_EVENT // A MAPPING-START event. MAPPING_END_EVENT // A MAPPING-END event. TAIL_COMMENT_EVENT )
Event types.
type FromYAMLNode ¶
FromYAMLNode is a new interface that types can implement to customize their unmarshaling behavior. It receives a Node directly and modifies the receiver in place. This is the preferred interface for new code.
Note: This interface is reserved for the v4 API and is not yet fully integrated into the current implementation.
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 LoadError ¶
type LoadError struct {
Stage Stage // Processing stage where error occurred
Message string // Error description
// Position information
Mark Mark // Primary error position
ContextMark Mark // Optional context position (e.g., start of construct)
ContextMsg string // Optional context message
// contains filtered or unexported fields
}
LoadError represents an error that occurred while loading a YAML document.
It provides detailed location information and identifies the processing stage where the error occurred.
func NewLoadError ¶
NewLoadError creates a LoadError with an underlying cause. The cause is accessible via Unwrap for use with errors.Is and errors.As.
type LoadErrors ¶
type LoadErrors struct {
Errors []*LoadError
}
LoadErrors is returned when one or more fields cannot be properly decoded.
func (*LoadErrors) As ¶
func (e *LoadErrors) As(target any) bool
As implements errors.As for Go versions prior to 1.20 that don't support the Unwrap() []error interface. It allows LoadErrors to match against *LoadError or *TypeError targets.
func (*LoadErrors) Error ¶
func (e *LoadErrors) Error() string
Error returns a formatted error message listing all construct errors.
type Loader ¶
type Loader struct {
// contains filtered or unexported fields
}
A Loader reads and loads YAML values from an input stream with configurable options.
func NewLoader ¶
NewLoader returns a new Loader that reads from r with the given options.
The Loader introduces its own buffering and may read data from r beyond the YAML values requested.
func (*Loader) ComposeAndResolve ¶
ComposeAndResolve composes and resolves the next document from the input and returns the node without constructing Go values. This is used by Unmarshal() to support the Unmarshaler interface.
func (*Loader) Load ¶
Load reads the next YAML-encoded document from its input and stores it in the value pointed to by v.
Returns io.EOF when there are no more documents to read. If WithSingleDocument option was set and a document was already read, subsequent calls return io.EOF.
Maps and pointers (to a struct, string, int, etc) are accepted as v values. If an internal pointer within a struct is not initialized, the yaml package will initialize it if necessary. The v parameter must not be nil.
Struct fields are only loaded if they are exported (have an upper case first letter), and are loaded 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 control the loading and dumping behavior.
See the documentation of the package-level Load function for more details about YAML to Go conversion and tag options.
func (*Loader) SetKnownFields ¶
SetKnownFields enables or disables strict field checking for subsequent Load calls. This is used by the legacy Decoder.KnownFields() method.
type MappingStyle ¶
type MappingStyle styleInt
MappingStyle represents the formatting style of a mapping node.
const ( // Let the emitter choose the style. ANY_MAPPING_STYLE MappingStyle = iota BLOCK_MAPPING_STYLE // The block mapping style. FLOW_MAPPING_STYLE // The flow mapping style. )
Mapping styles.
type Mark ¶
type Mark struct {
Index int // The position index.
Line int // The position line (1-indexed; 0 means unknown).
Column int // The position column (1-indexed; 0 means unknown).
}
Mark holds the pointer position.
type Marshaler ¶
Marshaler interface may be implemented by types to customize their behavior when being marshaled into a YAML document.
type Node ¶
type Node struct {
// Kind defines whether the node is a document, a mapping, a sequence,
// a scalar value, or an alias to another node. The specific data type of
// scalar nodes may be obtained via the ShortTag and LongTag methods.
Kind Kind
// Style allows customizing the appearance of the node in the tree.
Style Style
// Tag holds the YAML tag defining the data type for the value.
// When decoding, this field will always be set to the resolved tag,
// even when it wasn't explicitly provided in the YAML content.
// When encoding, if this field is unset the value type will be
// implied from the node properties, and if it is set, it will only
// be serialized into the representation if TaggedStyle is used or
// the implicit tag diverges from the provided one.
Tag string
// Value holds the unescaped and unquoted representation of the value.
Value string
// Anchor holds the anchor name for this node, which allows aliases to point to it.
Anchor string
// Alias holds the node that this alias points to. Only valid when Kind is AliasNode.
Alias *Node
// Content holds contained nodes for documents, mappings, and sequences.
Content []*Node
// HeadComment holds any comments in the lines preceding the node and
// not separated by an empty line.
HeadComment string
// LineComment holds any comments at the end of the line where the node is in.
LineComment string
// FootComment holds any comments following the node and before empty lines.
FootComment string
// Line and Column hold the node position in the decoded YAML text.
// These fields are not respected when encoding the node.
Line int
Column int
// Stream holds stream metadata (non-nil only when Kind == StreamNode).
Stream *Stream
}
Node represents an element in the YAML document hierarchy. While documents are typically encoded and decoded into higher level types, such as structs and maps, Node is an intermediate representation that allows detailed control over the content being decoded or encoded.
It's worth noting that although Node offers access into details such as line numbers, columns, and comments, the content when re-encoded will not have its original textual representation preserved. An effort is made to render the data pleasantly, and to preserve comments near the data they describe, though.
Values that make use of the Node type interact with the yaml package in the same way any other type would do, by encoding and decoding yaml data directly or indirectly into them.
For example:
var person struct {
Name string
Address yaml.Node
}
err := yaml.Unmarshal(data, &person)
Or by itself:
var person Node err := yaml.Unmarshal(data, &person)
func (*Node) Decode ¶
Decode decodes the node and stores its data into the value pointed to by v.
See the documentation for Unmarshal for details about the conversion of YAML into a Go value.
func (*Node) Dump ¶
Dump encodes value v and stores its representation in n, applying the given options.
This method is useful when you need to apply specific encoding options while building Node trees programmatically.
See the documentation for Marshal for details about the conversion of Go values into YAML.
func (*Node) Encode ¶
Encode encodes value v and stores its representation in n.
See the documentation for Marshal for details about the conversion of Go values into YAML.
func (*Node) Load ¶
Load decodes the node and stores its data into the value pointed to by v, applying the given options.
This method is useful when you need to preserve options like WithKnownFields() inside custom UnmarshalYAML implementations.
Maps and pointers (to a struct, string, int, etc) are accepted as v values. If an internal pointer within a struct is not initialized, the yaml package will initialize it if necessary. The v parameter must not be nil.
See the documentation of the package-level Load function for details about YAML to Go conversion and tag options.
func (*Node) LongTag ¶
LongTag returns the long form of the tag that indicates the data type for the node. If the Tag field isn't explicitly defined, one will be computed based on the node properties.
type Option ¶
Option allows configuring YAML loading and dumping operations.
func CombineOptions ¶
CombineOptions combines multiple options into a single Option. This is useful for creating option presets or combining version defaults with custom options.
func WithAllDocuments ¶
WithAllDocuments enables multi-document mode for Load and Dump operations.
When used with Load, the target must be a pointer to a slice. All documents in the YAML stream will be decoded into the slice. Zero documents results in an empty slice (no error).
When used with Dump, the input must be a slice. Each element will be encoded as a separate YAML document with "---" separators.
When called without arguments, defaults to true.
The default is false (single-document mode).
func WithCanonical ¶
WithCanonical forces canonical YAML output format.
When enabled, the encoder outputs strictly canonical YAML with explicit tags for all values. This produces verbose output primarily useful for debugging and YAML spec compliance testing. When called without arguments, defaults to true.
The default is false.
func WithCompactSeqIndent ¶
WithCompactSeqIndent configures whether the sequence indicator '- ' is considered part of the indentation when dumping YAML content.
If compact is true, '- ' is treated as part of the indentation. If compact is false, '- ' is not treated as part of the indentation. When called without arguments, defaults to true.
func WithExplicitEnd ¶
WithExplicitEnd controls whether document end markers (...) are always emitted.
When true, every document ends with an explicit "..." marker. When false (default), the marker is omitted. When called without arguments, defaults to true.
func WithExplicitStart ¶
WithExplicitStart controls whether document start markers (---) are always emitted.
When true, every document begins with an explicit "---" marker. When false (default), the marker is omitted for the first document. When called without arguments, defaults to true.
func WithFlowSimpleCollections ¶
WithFlowSimpleCollections controls whether simple collections use flow style.
When true, sequences and mappings containing only scalar values (no nested collections) are rendered in flow style if they fit within the line width. Example: {name: test, count: 42} or [a, b, c] When called without arguments, defaults to true.
When false (default), all collections use block style.
func WithIndent ¶
WithIndent sets the number of spaces to use for indentation when dumping YAML content.
Valid values are 2-9. Common choices: 2 (compact), 4 (readable).
func WithKnownFields ¶
WithKnownFields enables or disables strict field checking during YAML loading.
When enabled, loading will return an error if the YAML input contains fields that do not correspond to any fields in the target struct. When called without arguments, defaults to true.
func WithLineBreak ¶
WithLineBreak sets the line ending style for YAML output.
Available options:
- LineBreakLN: Unix-style \n (default)
- LineBreakCR: Old Mac-style \r
- LineBreakCRLN: Windows-style \r\n
The default is LineBreakLN.
func WithLineWidth ¶
WithLineWidth sets the preferred line width for YAML output.
When encoding long strings, the encoder will attempt to wrap them at this width using literal block style (|). Set to -1 or 0 for unlimited width.
The default is 80 characters.
func WithQuotePreference ¶
func WithQuotePreference(style QuoteStyle) Option
WithQuotePreference sets the preferred quote style for strings that require quoting.
This option only affects strings that require quoting per the YAML spec. Plain strings that don't need quoting remain unquoted regardless of this setting. Quoting is required for:
- Strings that look like other YAML types (true, false, null, 123, etc.)
- Strings with leading/trailing whitespace
- Strings containing special YAML syntax characters
- Empty strings in certain contexts
Quote styles:
- QuoteSingle: Use single quotes (v4 default)
- QuoteDouble: Use double quotes
- QuoteLegacy: Legacy v2/v3 behavior (mixed quoting)
func WithSingleDocument ¶
WithSingleDocument configures the Loader to only process the first document in a YAML stream. After the first document is loaded, subsequent calls to Load will return io.EOF.
When called without arguments, defaults to true.
This is useful when you expect exactly one document and want behavior similar to [Unmarshal].
func WithStreamNodes ¶
WithStreamNodes enables returning stream boundary nodes when loading YAML.
When enabled, Loader.Load returns an interleaved sequence of StreamNode and DocumentNode values:
[StreamNode, DocNode, StreamNode, DocNode, ..., StreamNode]
StreamNodes contain metadata about the stream including:
- Encoding (UTF-8, UTF-16LE, UTF-16BE)
- YAML version directive (%YAML)
- Tag directives (%TAG)
- Position information (Line, Column)
An empty YAML stream returns a single StreamNode. When called without arguments, defaults to true.
The default is false.
func WithUnicode ¶
WithUnicode controls whether non-ASCII characters are allowed in YAML output.
When true, non-ASCII characters appear as-is (e.g., "café"). When false, non-ASCII characters are escaped (e.g., "caf\u00e9"). When called without arguments, defaults to true.
The default is true.
func WithUniqueKeys ¶
WithUniqueKeys enables or disables duplicate key detection during YAML loading.
When enabled, loading will return an error if the YAML input contains duplicate keys in any mapping. This is a security feature that prevents key override attacks. When called without arguments, defaults to true.
The default is true.
type Options ¶
type Options struct {
// Loading options
KnownFields bool // Enforce known fields in structs
SingleDocument bool // Only load first document
UniqueKeys bool // Enforce unique keys in mappings
StreamNodes bool // Enable stream node emission
AllDocuments bool // Load/Dump all documents in multi-document streams
// Dumping options
Indent int // Indentation spaces (2-9)
CompactSeqIndent bool // Whether '- ' counts as indentation
LineWidth int // Preferred line width (-1 for unlimited)
Unicode bool // Allow non-ASCII characters
Canonical bool // Canonical YAML output
LineBreak LineBreak // Line ending style
ExplicitStart bool // Always emit ---
ExplicitEnd bool // Always emit ...
FlowSimpleCollections bool // Use flow style for simple collections
QuotePreference QuoteStyle // Preferred quote style when quoting is required
// Safety limit checks (set by ApplyOptions or WithPlugin(limit.New(...)))
DepthCheck func(depth int, ctx *DepthContext) error
AliasCheck func(aliasCount, constructCount int) error
// Private options (not exported, used internally)
FromLegacy bool // Indicates legacy Unmarshal()/Decoder path (check Unmarshaler, allow trailing content)
}
Options holds configuration for both loading and dumping YAML.
func ApplyOptions ¶
ApplyOptions applies the given options to a new options struct. Starts with v4 defaults.
type Parser ¶
type Parser struct {
HeadComment []byte // The current head comments
LineComment []byte // The current line comments
FootComment []byte // The current foot comments
// contains filtered or unexported fields
}
Parser structure holds all information about the current state of the parser.
func (*Parser) GetCommentsHead ¶
GetCommentsHead returns the current position in the comment queue.
func (*Parser) GetPendingComments ¶
GetPendingComments returns the parser's comment queue for CLI access.
func (*Parser) SetEncoding ¶
SetEncoding sets the source encoding.
func (*Parser) SetInputReader ¶
SetInputReader sets a file input.
func (*Parser) SetInputString ¶
SetInputString sets a string input.
func (*Parser) SetSkipComments ¶
SetSkipComments enables or disables comment scanning. When enabled, the scanner skips comment tokens for better performance.
func (*Parser) UnfoldComments ¶
UnfoldComments walks through the comments queue and joins all comments behind the position of the provided token into the respective top-level comment slices in the parser.
type ParserState ¶
type ParserState int
ParserState represents the state of the parser.
const ( PARSE_STREAM_START_STATE ParserState = iota PARSE_IMPLICIT_DOCUMENT_START_STATE // Expect the beginning of an implicit document. PARSE_DOCUMENT_START_STATE // Expect DOCUMENT-START. PARSE_DOCUMENT_CONTENT_STATE // Expect the content of a document. PARSE_DOCUMENT_END_STATE // Expect DOCUMENT-END. PARSE_BLOCK_NODE_STATE // Expect a block node. PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a block sequence. PARSE_BLOCK_SEQUENCE_ENTRY_STATE // Expect an entry of a block sequence. PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE // Expect an entry of an indentless sequence. PARSE_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. PARSE_BLOCK_MAPPING_KEY_STATE // Expect a block mapping key. PARSE_BLOCK_MAPPING_VALUE_STATE // Expect a block mapping value. PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a flow sequence. PARSE_FLOW_SEQUENCE_ENTRY_STATE // Expect an entry of a flow sequence. PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE // Expect a key of an ordered mapping. PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE // Expect a value of an ordered mapping. PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE // Expect the and of an ordered mapping entry. PARSE_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. PARSE_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. PARSE_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE // Expect an empty value of a flow mapping. PARSE_END_STATE // Expect nothing. )
Parser state constants define the different states the parser can be in.
func (ParserState) String ¶
func (ps ParserState) String() string
String returns a string representation of the parser state.
type QuoteStyle ¶
type QuoteStyle int
QuoteStyle represents the preferred quote style for scalar values.
const ( QuoteSingle QuoteStyle = iota // Prefer single quotes when quoting is required. QuoteDouble // Prefer double quotes when quoting is required. QuoteLegacy // Legacy behavior: double in representer, single in emitter. )
Quote style types for required quoting.
func (QuoteStyle) ScalarStyle ¶
func (q QuoteStyle) ScalarStyle() ScalarStyle
ScalarStyle returns the scalar style for this quote preference in the representer/serializer context. In this context, both QuoteDouble and QuoteLegacy use double quotes.
type ReadHandler ¶
ReadHandler is called by the Parser when it needs to read more bytes from the input source. The handler should fill the provided buffer with up to len(buffer) bytes from the input source.
The arguments are as follows:
[in] parser The parser object. [out] buffer The buffer for reading. [out] size_read The actual number of bytes read from the source.
On success, the handler should return 1. If the handler failed, the returned value should be 0. On EOF, the handler should set the size_read to 0 and return 1.
type Representer ¶
type Representer struct {
Indent int
// contains filtered or unexported fields
}
Representer converts Go values to YAML node trees with configurable formatting options.
func NewRepresenter ¶
func NewRepresenter(opts *Options) *Representer
NewRepresenter creates a new YAML representer with the given options.
type Resolver ¶
type Resolver struct {
// contains filtered or unexported fields
}
Resolver handles tag resolution for YAML nodes.
func NewResolver ¶
NewResolver creates a new Resolver with the given options.
type ScalarConstructFunc ¶
ScalarConstructFunc is the signature for tag-specific scalar constructor functions. Each function handles construction of a specific YAML tag to various Go types.
type ScalarStyle ¶
type ScalarStyle styleInt
ScalarStyle represents the formatting style of a scalar value.
const ( // Let the emitter choose the style. ANY_SCALAR_STYLE ScalarStyle = 0 PLAIN_SCALAR_STYLE ScalarStyle = 1 << iota // The plain scalar style. SINGLE_QUOTED_SCALAR_STYLE // The single-quoted scalar style. DOUBLE_QUOTED_SCALAR_STYLE // The double-quoted scalar style. LITERAL_SCALAR_STYLE // The literal scalar style. FOLDED_SCALAR_STYLE // The folded scalar style. )
Scalar styles.
func (ScalarStyle) String ¶
func (style ScalarStyle) String() string
String returns a string representation of a ScalarStyle.
type SequenceStyle ¶
type SequenceStyle styleInt
SequenceStyle represents the formatting style of a sequence node.
const ( // Let the emitter choose the style. ANY_SEQUENCE_STYLE SequenceStyle = iota BLOCK_SEQUENCE_STYLE // The block sequence style. FLOW_SEQUENCE_STYLE // The flow sequence style. )
Sequence styles.
type Serializer ¶
type Serializer struct {
Emitter Emitter
// contains filtered or unexported fields
}
Serializer handles serialization of YAML nodes to event stream.
func NewSerializer ¶
func NewSerializer(w io.Writer, opts *Options) *Serializer
NewSerializer creates a new Serializer with the given options.
func (*Serializer) Finish ¶
func (s *Serializer) Finish()
Finish completes serialization by emitting a STREAM_END event.
func (*Serializer) Serialize ¶
func (s *Serializer) Serialize(node *Node)
Serialize walks a Node tree and emits events to produce YAML output. This is the primary method for the Serializer stage.
type SimpleKey ¶
type SimpleKey struct {
// contains filtered or unexported fields
}
SimpleKey holds information about a potential simple key.
type Stage ¶
type Stage string
Stage identifies the processing stage where an error occurred during YAML loading or dumping.
const ( // Load stages ReaderStage Stage = "reader" // Input reading and encoding ScannerStage Stage = "scanner" // Tokenization ParserStage Stage = "parser" // Event stream parsing ComposerStage Stage = "composer" // Node tree construction ResolverStage Stage = "resolver" // Tag resolution ConstructorStage Stage = "constructor" // Go value construction // Dump stages RepresenterStage Stage = "representer" // Go value to Node tree SerializerStage Stage = "serializer" // Node tree to events EmitterStage Stage = "emitter" // Events to YAML bytes WriterStage Stage = "writer" // Output writing )
type Stream ¶
type Stream struct {
Encoding Encoding
Version *StreamVersionDirective
TagDirectives []StreamTagDirective
}
Stream holds stream-level metadata for StreamNode. This includes encoding, version directive, and tag directives.
type StreamTagDirective ¶
StreamTagDirective represents a YAML %TAG directive for stream nodes.
type StreamVersionDirective ¶
StreamVersionDirective represents a YAML %YAML version directive for stream nodes.
type TagDirective ¶
type TagDirective struct {
// contains filtered or unexported fields
}
TagDirective holds the YAML tag directive data.
func (*TagDirective) GetHandle ¶
func (t *TagDirective) GetHandle() string
GetHandle returns the tag handle.
func (*TagDirective) GetPrefix ¶
func (t *TagDirective) GetPrefix() string
GetPrefix returns the tag prefix.
type ToYAMLNode ¶
ToYAMLNode is a new interface that types can implement to customize their marshaling behavior. It returns a Node directly. This is the preferred interface for new code.
Note: This interface is reserved for the v4 API and is not yet fully integrated into the current implementation.
type Token ¶
type Token struct {
// The token type.
Type TokenType
// The start/end of the token.
StartMark, EndMark Mark
// The alias/anchor/scalar Value or tag/tag directive handle
// (for ALIAS_TOKEN, ANCHOR_TOKEN, SCALAR_TOKEN, TAG_TOKEN, TAG_DIRECTIVE_TOKEN).
Value []byte
// The scalar Style (for SCALAR_TOKEN).
Style ScalarStyle
// contains filtered or unexported fields
}
Token holds information about a scanning token.
type TokenType ¶
type TokenType int
TokenType represents the type of a scanned token.
const ( // An empty token. NO_TOKEN TokenType = iota STREAM_START_TOKEN // A STREAM-START token. STREAM_END_TOKEN // A STREAM-END token. VERSION_DIRECTIVE_TOKEN // A VERSION-DIRECTIVE token. TAG_DIRECTIVE_TOKEN // A TAG-DIRECTIVE token. DOCUMENT_START_TOKEN // A DOCUMENT-START token. DOCUMENT_END_TOKEN // A DOCUMENT-END token. BLOCK_SEQUENCE_START_TOKEN // A BLOCK-SEQUENCE-START token. BLOCK_MAPPING_START_TOKEN // A BLOCK-SEQUENCE-END token. BLOCK_END_TOKEN // A BLOCK-END token. FLOW_SEQUENCE_START_TOKEN // A FLOW-SEQUENCE-START token. FLOW_SEQUENCE_END_TOKEN // A FLOW-SEQUENCE-END token. FLOW_MAPPING_START_TOKEN // A FLOW-MAPPING-START token. FLOW_MAPPING_END_TOKEN // A FLOW-MAPPING-END token. BLOCK_ENTRY_TOKEN // A BLOCK-ENTRY token. FLOW_ENTRY_TOKEN // A FLOW-ENTRY token. KEY_TOKEN // A KEY token. VALUE_TOKEN // A VALUE token. ALIAS_TOKEN // An ALIAS token. ANCHOR_TOKEN // An ANCHOR token. TAG_TOKEN // A TAG token. SCALAR_TOKEN // A SCALAR token. COMMENT_TOKEN // A COMMENT token. )
Token types.
type TypeError
deprecated
type TypeError struct {
Errors []string
}
TypeError is a legacy error type retained for compatibility.
A TypeError is returned by Unmarshal when one or more fields in the YAML document cannot be properly decoded into the requested types. When this error is returned, the value is still unmarshaled partially.
Deprecated: Use LoadErrors instead.
type Unmarshaler ¶
Unmarshaler is the interface implemented by types that can unmarshal a YAML description of themselves.
type VersionDirective ¶
type VersionDirective struct {
// contains filtered or unexported fields
}
VersionDirective holds the YAML version directive data.
func (*VersionDirective) Major ¶
func (v *VersionDirective) Major() int
Major returns the major version number.
func (*VersionDirective) Minor ¶
func (v *VersionDirective) Minor() int
Minor returns the minor version number.
type WriteHandler ¶
WriteHandler is called when the Emitter needs to flush the accumulated characters to the output. The handler should write @a size bytes of the @a buffer to the output.
@param[in,out] data A pointer to an application data specified by
yamlEmitter.setOutput().
@param[in] buffer The buffer with bytes to be written.
@param[in] size The size of the buffer.
@returns On success, the handler should return @c 1. If the handler failed,
the returned value should be @c 0.
type WriterError ¶
type WriterError struct {
Err error
}
WriterError represents an error that occurred while writing output.
func (WriterError) Unwrap ¶
func (e WriterError) Unwrap() error
Unwrap returns the underlying error.