libyaml

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: Apache-2.0 Imports: 18 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

internal/libyaml

This package implements the YAML processing pipeline used by the public github.com/pb33f/go-yaml API. It includes the Go port of libyaml's low-level machinery and the stages that convert between YAML nodes and Go values. Applications should import the public package rather than this internal one.

Processing Stages

Operation Stages Source files
Load text Reader, scanner, parser reader.go, scanner.go, parser.go
Build nodes Composer, resolver composer.go, resolver.go
Build Go values Constructor constructor.go, plugin_merge_key.go
Build output nodes Representer, desolver representer.go, desolver.go
Write text Serializer, emitter, writer serializer.go, emitter.go, writer.go

loader.go and dumper.go coordinate these stages. node.go defines nodes and their conversion methods. yaml.go defines token, event, encoding, style, and mark types. options.go supplies options and default safety checks. errors.go defines structured errors.

The reader, scanner, and parser share the Parser state. Parser.Parse pulls tokens from the scanner and returns events. Composer.Compose builds node graphs, including anchor and alias edges. The resolver infers scalar tags; the constructor converts nodes into the requested destination types. On output, the serializer pushes events to the emitter, which writes formatted YAML through the writer.

See go-yaml Internals for control flow, comments, safety limits, and plugin boundaries.

Test Layout

Stage tests live in *_test.go, with YAML fixtures in testdata/. Examples include scanner.yaml, parser.yaml, composer.yaml, constructor.yaml, representer.yaml, desolver.yaml, serializer.yaml, emitter.yaml, reader.yaml, and writer.yaml. Not every test file has a fixture; several tests construct their inputs in Go.

The shared data-driven framework is in internal/testutil/datatest. This package's testdata_test.go supplies TestCase, constant and event converters, and LoadTestCases for its fixtures. Fixture YAML is loaded through LoadAny, so ordinary scalar resolution applies before conversion to test case structs. Quote fixture strings when they would otherwise resolve to another type.

Test cases use the test type as a mapping key:

- scan-tokens:
    name: Simple scalar
    yaml: hello
    want:
    - STREAM_START_TOKEN
    - SCALAR_TOKEN
    - STREAM_END_TOKEN

A parser case can inspect event boundaries:

- parse-events:
    name: Simple mapping
    yaml: |
      key: value
    want:
    - STREAM_START_EVENT
    - DOCUMENT_START_EVENT
    - MAPPING_START_EVENT
    - SCALAR_EVENT
    - SCALAR_EVENT
    - MAPPING_END_EVENT
    - DOCUMENT_END_EVENT
    - STREAM_END_EVENT

name, yaml, and want are common fixture fields. Emitter tests use data for event specifications and conf for emitter configuration. Detailed scanner and parser tests can specify token or event properties such as value and style. Use the corresponding test handler and nearby fixtures as the source of truth for a test type's accepted fields. There is no separate scalar-resolution algorithm for test data.

Running Tests

Run these commands from the repository root:

make test-internal
make shell CMD='go test ./internal/libyaml -run TestScanner'
make shell CMD='go test ./internal/libyaml -run TestParser'
make shell CMD='go test ./internal/libyaml -run TestEmitter'
make shell CMD='go test -v ./internal/libyaml -run TestScanner/Simple_scalar'
make shell CMD='go test -cover ./internal/libyaml'

The test-only module under testdata/v3hooks checks real v3 unmarshaler types without adding those modules to the core dependency graph. Run it with make test-v3-hooks.

Documentation

Overview

Package libyaml implements go-yaml's internal load and dump pipelines. It combines libyaml-derived scanning, parsing, and emitting with node composition, tag resolution, Go value construction, and representation. Applications should use github.com/pb33f/go-yaml rather than this internal package.

Index

Constants

View Source
const (
	// NULL_TAG is the tag !!null with the only possible value: null.
	NULL_TAG = "tag:yaml.org,2002:null"
	// BOOL_TAG is the tag !!bool with the values: true and false.
	BOOL_TAG = "tag:yaml.org,2002:bool"
	// STR_TAG is the tag !!str for string values.
	STR_TAG = "tag:yaml.org,2002:str"
	// INT_TAG is the tag !!int for integer values.
	INT_TAG = "tag:yaml.org,2002:int"
	// FLOAT_TAG is the tag !!float for float values.
	FLOAT_TAG = "tag:yaml.org,2002:float"
	// TIMESTAMP_TAG is the tag !!timestamp for date and time values.
	TIMESTAMP_TAG = "tag:yaml.org,2002:timestamp"
	// SEQ_TAG is the tag !!seq for sequences.
	SEQ_TAG = "tag:yaml.org,2002:seq"
	// MAP_TAG is the tag !!map for mappings.
	MAP_TAG = "tag:yaml.org,2002:map"
)

Possible values for Node.Tag

View Source
const (
	// BINARY_TAG is the tag !!binary for binary data.
	BINARY_TAG = "tag:yaml.org,2002:binary"
	// MERGE_TAG is the tag !!merge for merging mappings.
	MERGE_TAG = "tag:yaml.org,2002:merge"
	// DEFAULT_SCALAR_TAG is the default tag for scalars, which is !!str.
	DEFAULT_SCALAR_TAG = STR_TAG
	// DEFAULT_SEQUENCE_TAG is the default tag for sequences, which is !!seq.
	DEFAULT_SEQUENCE_TAG = SEQ_TAG
	// DEFAULT_MAPPING_TAG is the default tag for mappings, which is !!map.
	DEFAULT_MAPPING_TAG = MAP_TAG
)

Additional possible values for Node.Tag These are the tags that are not in the original libyaml but are used in go-yaml for specific purposes.

Variables

View Source
var DefaultOptions = &Options{
	Indent:          4,
	LineWidth:       -1,
	Unicode:         true,
	UniqueKeys:      true,
	QuotePreference: QuoteLegacy,

	DepthCheck: DefaultDepthCheck,
	AliasCheck: DefaultAliasCheck,
}

DefaultOptions holds the default options for APIs that don't accept options.

Functions

func DefaultAliasCheck

func DefaultAliasCheck(aliasCount, constructCount int) error

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

func Dump(in any, opts ...Option) (out []byte, err error)

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 yaml.Marshal for details.

func Fail

func Fail(err error)

Fail panics with a YAMLError wrapping the given error.

func Load

func Load(in []byte, out any, opts ...Option) error

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

func LoadAny(data []byte) (any, error)

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

func ParserGetEvents(in []byte) (string, error)

ParserGetEvents parses the YAML input and returns the generated event stream.

func SetLegacyAllowTrailingContent

func SetLegacyAllowTrailingContent(o *Options)

SetLegacyAllowTrailingContent sets the internal allowLegacyTrailingContent flag to true.

This function is not exported out of the module and is used in [yaml.NewDecoder] and [yaml.Unmarshal] to indicate that the legacy behavior of allowing trailing content after a document should be enabled for backward compatibility.

Types

type AliasData

type AliasData struct {
	// contains filtered or unexported fields
}

AliasData holds information about aliases.

type AliasDataContext added in v0.2.0

type AliasDataContext interface {
	BeginDocument() error
	DefineAnchor(name string, node *Node) error
	ResolveAlias(name string) (node *Node, found bool, err error)
	EndDocument() error
}

AliasDataContext owns anchor definitions and alias lookup for one stream. DefineAnchor receives a live node, before its children have been composed. Policies may retain that pointer but must not change the node. ResolveAlias must return a data node when found is true. External targets must have resolved tags; locally defined targets are resolved by the host. YAML null is represented by a scalar null node, never a nil pointer. EndDocument is called only after successful composition. Contexts must not retain open resources; there is no teardown callback.

func NewAliasDataPolicy added in v0.2.0

func NewAliasDataPolicy(sources AliasDataSources) AliasDataContext

NewAliasDataPolicy constructs an independent node-based anchor policy.

type AliasDataPlugin added in v0.2.0

type AliasDataPlugin interface {
	NewAliasDataContext(AliasDataServices) (AliasDataContext, error)
}

AliasDataPlugin creates an independent anchor policy for each input stream. Implementations must support concurrent calls to NewAliasDataContext.

type AliasDataServices added in v0.2.0

type AliasDataServices struct {
	NewNode     func(any) (*Node, error)
	LoadFile    func(string) (*Node, error)
	Environment func() map[string]string
}

AliasDataServices supplies operation-local conversions and source snapshots. NewNode copies node graphs and converts Go values through the representer. LoadFile loads exactly one mapping document with the selected parser and ordinary document-scoped aliases, without consulting external alias data. Its copied nodes retain tags, styles, and scalar text; root merges are applied.

type AliasDataSources added in v0.2.0

type AliasDataSources struct {
	Data, File, Env       map[string]*Node
	Stream, Path, Disable bool
}

AliasDataSources holds resolved, operation-local source nodes. This is an internal implementation detail shared with plugin/aliasdata.

type Comment

type Comment struct {
	// ScanMark is the position where scanning for comments started
	ScanMark Mark
	// TokenMark is the position after which tokens will be associated with this comment
	TokenMark Mark
	// StartMark is the position of the '#' comment mark
	StartMark Mark
	// EndMark is the position where the comment ended
	EndMark Mark

	Head []byte
	Line []byte
	Foot []byte
}

Comment holds information about a comment in the YAML stream.

type Composer

type Composer struct {
	Parser Parser

	Textless bool
	// contains filtered or unexported fields
}

Composer produces a node tree out of a libyaml event stream.

func NewComposer

func NewComposer(b []byte, opts *Options) *Composer

NewComposer creates a new composer from a byte slice.

func NewComposerFromEvents

func NewComposerFromEvents(events []Event, opts *Options) *Composer

NewComposerFromEvents creates a composer that reads an existing event stream instead of parsing YAML text.

func NewComposerFromReader

func NewComposerFromReader(r io.Reader, opts *Options) *Composer

NewComposerFromReader creates a new composer from an io.Reader.

func (*Composer) Compose

func (c *Composer) Compose() *Node

Compose composes the next YAML node from the event stream.

func (*Composer) Destroy

func (c *Composer) Destroy()

Destroy cleans up the composer by deleting any pending event and the underlying parser.

func (*Composer) SetStreamNodes

func (c *Composer) SetStreamNodes(enable bool)

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 DefaultMergeKey added in v0.2.0

type DefaultMergeKey struct {
	Config MergeKeyConfig
}

DefaultMergeKey implements the standard shallow merge algorithm. The algorithm itself lives in the internal plugin package.

func (DefaultMergeKey) MergeKeyConfig added in v0.2.0

func (p DefaultMergeKey) MergeKeyConfig() MergeKeyConfig

MergeKeyConfig returns the configuration by value.

func (DefaultMergeKey) MergeMappings added in v0.2.0

func (p DefaultMergeKey) MergeMappings(in MergeKeyInput) (*Node, error)

MergeMappings adapts YAML nodes to the default plugin algorithm.

type DepthContext

type DepthContext struct {
	Kind DepthKind
}

DepthContext holds context about a nesting depth check.

type DepthKind

type DepthKind string

DepthKind represents the type of nesting (flow or block).

const (
	// DepthKindFlow represents flow-style nesting (inside [] or {}).
	DepthKindFlow DepthKind = "flow"
	// DepthKindBlock represents block-style nesting (inside indentation).
	DepthKindBlock DepthKind = "block"
)

DepthKind constants for nesting depth checks.

They are the possible values for DepthContext.Kind when checking the nesting depth of YAML nodes.

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

func NewDesolver(opts *Options) *Desolver

NewDesolver creates a new Desolver with the given options.

func (*Desolver) Desolve

func (d *Desolver) Desolve(n *Node) (tag string, style Style)

Desolve returns the tag and style that n should be serialized with, once tags that can be inferred are removed. This is the inverse of Resolver - it takes a node of 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.

Desolve does not modify n, which may be part of a tree owned by the caller.

type DumpError

type DumpError struct {
	// Stage identifies the processing stage where the error occurred.
	Stage Stage
	// Message provides a description of the error.
	Message string
	// 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

func NewDumpError(stage Stage, message string, cause error) *DumpError

NewDumpError creates a DumpError with an underlying cause. The cause is accessible via Unwrap for use with errors.Is and errors.As.

func (*DumpError) Error

func (e *DumpError) Error() string

Error returns the error message with stage information. Format: "go-yaml dump error in <stage>: <message>"

func (*DumpError) Unwrap

func (e *DumpError) Unwrap() error

Unwrap returns the underlying error.

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:

  1. Representer: Go values → Tagged Node tree
  2. Desolver: Remove inferable tags
  3. Serializer: Node tree → Events → YAML

The Serializer applies the Desolver to each node as it serializes it, so that the tree is never modified: it may contain nodes owned by the caller.

func NewDumper

func NewDumper(w io.Writer, opts ...Option) (*Dumper, error)

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

func (d *Dumper) Close() (err error)

Close closes the Dumper by writing any remaining data. It does not write a stream terminating string "...".

func (*Dumper) Dump

func (d *Dumper) Dump(v any) (err error)

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 yaml.Marshal for details about the conversion of Go values to YAML.

func (*Dumper) SetLegacyEncoderCompactSeqIndent

func (d *Dumper) SetLegacyEncoderCompactSeqIndent(compact bool)

SetLegacyEncoderCompactSeqIndent allows changing the compact sequence indentation for the legacy Encoder API.

This method is only provided for backward compatibility with the legacy Encoder API. Do not use in libyaml, use WithCompactSeqIndent instead.

func (*Dumper) SetLegacyEncoderIndent

func (d *Dumper) SetLegacyEncoderIndent(spaces int)

SetLegacyEncoderIndent allows changing the indentation for the legacy Encoder API.

This method is only provided for backward compatibility with the legacy Encoder API. Do not use in libyaml, use WithIndent instead.

type Emitter

type Emitter struct {

	// BestIndent is the number of spaces to use for indentation.
	BestIndent int

	// CompactSequenceIndent is true if the '- ' is considered part of the indentation for sequence elements.
	CompactSequenceIndent bool

	// OpenEnded is true if an explicit document end is required.
	OpenEnded bool

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

func NewEmitter() Emitter

NewEmitter creates a new emitter object.

func (*Emitter) Delete

func (emitter *Emitter) Delete()

Delete an emitter object.

func (*Emitter) Emit

func (emitter *Emitter) Emit(event *Event) error

Emit an event.

func (*Emitter) SetCanonical

func (emitter *Emitter) SetCanonical(canonical bool)

SetCanonical sets the canonical output style.

func (*Emitter) SetEncoding

func (emitter *Emitter) SetEncoding(encoding Encoding)

SetEncoding sets the output encoding.

func (*Emitter) SetIndent

func (emitter *Emitter) SetIndent(indent int)

SetIndent sets the indentation increment.

func (*Emitter) SetLineBreak

func (emitter *Emitter) SetLineBreak(line_break LineBreak)

SetLineBreak sets the preferred line break character.

func (*Emitter) SetOutputString

func (emitter *Emitter) SetOutputString(output_buffer *[]byte)

SetOutputString sets a string output.

func (*Emitter) SetOutputWriter

func (emitter *Emitter) SetOutputWriter(w io.Writer)

SetOutputWriter sets a file output.

func (*Emitter) SetUnicode

func (emitter *Emitter) SetUnicode(unicode bool)

SetUnicode sets if unescaped non-ASCII characters are allowed.

func (*Emitter) SetWidth

func (emitter *Emitter) SetWidth(width int)

SetWidth sets the preferred line width.

type EmitterError

type EmitterError struct {
	Message string
}

EmitterError represents an error that occurred during emitting.

func (EmitterError) Error

func (e EmitterError) Error() string

Error returns the error message.

type EmitterState

type EmitterState int

EmitterState represents the current state of the emitter.

const (
	// EMIT_STREAM_START_STATE expects STREAM-START.
	EMIT_STREAM_START_STATE EmitterState = iota

	// EMIT_FIRST_DOCUMENT_START_STATE expects the first DOCUMENT-START or STREAM-END.
	EMIT_FIRST_DOCUMENT_START_STATE
	// EMIT_DOCUMENT_START_STATE expects DOCUMENT-START.
	EMIT_DOCUMENT_START_STATE
	// EMIT_DOCUMENT_CONTENT_STATE expects the content of a document.
	EMIT_DOCUMENT_CONTENT_STATE
	// EMIT_DOCUMENT_END_STATE expects DOCUMENT-END.
	EMIT_DOCUMENT_END_STATE
	// EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE expects the first item of a flow sequence.
	EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE
	// EMIT_FLOW_SEQUENCE_TRAIL_ITEM_STATE expects the next item of a flow sequence, with the comma already written out.
	EMIT_FLOW_SEQUENCE_TRAIL_ITEM_STATE
	// EMIT_FLOW_SEQUENCE_ITEM_STATE expects an item of a flow sequence.
	EMIT_FLOW_SEQUENCE_ITEM_STATE
	// EMIT_FLOW_MAPPING_FIRST_KEY_STATE expects the first key of a flow mapping.
	EMIT_FLOW_MAPPING_FIRST_KEY_STATE
	// EMIT_FLOW_MAPPING_TRAIL_KEY_STATE expects the next key of a flow mapping, with the comma already written out
	EMIT_FLOW_MAPPING_TRAIL_KEY_STATE
	// EMIT_FLOW_MAPPING_KEY_STATE expects a key of a flow mapping.
	EMIT_FLOW_MAPPING_KEY_STATE
	// EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE expects a value for a simple key of a flow mapping.
	EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE
	// EMIT_FLOW_MAPPING_VALUE_STATE expects a value of a flow mapping.
	EMIT_FLOW_MAPPING_VALUE_STATE
	// EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE expects the first item of a block sequence.
	EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE
	// EMIT_BLOCK_SEQUENCE_ITEM_STATE expects an item of a block sequence.
	EMIT_BLOCK_SEQUENCE_ITEM_STATE
	// EMIT_BLOCK_MAPPING_FIRST_KEY_STATE expects the first key of a block mapping.
	EMIT_BLOCK_MAPPING_FIRST_KEY_STATE
	// EMIT_BLOCK_MAPPING_KEY_STATE expects the key of a block mapping.
	EMIT_BLOCK_MAPPING_KEY_STATE
	// EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE expects a value for a simple key of a block mapping.
	EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE
	// EMIT_BLOCK_MAPPING_VALUE_STATE expects a value of a block mapping.
	EMIT_BLOCK_MAPPING_VALUE_STATE
	// EMIT_END_STATE expects nothing.
	EMIT_END_STATE
)

Possible EmitterState values. The transitions between these states are managed internally by the emitter.

type Encoding

type Encoding int

Encoding represents the character encoding of a YAML stream.

const (
	// ANY_ENCODING lets the parser choose the encoding.
	ANY_ENCODING Encoding = iota

	// UTF8_ENCODING uses UTF-8 encoding (default).
	UTF8_ENCODING
	// UTF16LE_ENCODING uses UTF-16-LE encoding with BOM.
	UTF16LE_ENCODING
	// UTF16BE_ENCODING uses UTF-16-BE encoding with BOM.
	UTF16BE_ENCODING
)

Possible Encoding values.

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 when cannot allocate or reallocate a block of memory.
	MEMORY_ERROR
	// READER_ERROR when cannot read or decode the input stream.
	READER_ERROR
	// SCANNER_ERROR when cannot scan the input stream.
	SCANNER_ERROR
	// PARSER_ERROR when cannot parse the input stream.
	PARSER_ERROR
	// COMPOSER_ERROR when cannot compose a YAML document.
	COMPOSER_ERROR
	// WRITER_ERROR when cannot write to the output stream.
	WRITER_ERROR
	// EMITTER_ERROR when cannot emit a YAML stream.
	EMITTER_ERROR
)

Possible ErrorType values. 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

func NewAliasEvent(anchor []byte) Event

NewAliasEvent creates a new ALIAS event.

func NewDocumentEndEvent

func NewDocumentEndEvent(implicit bool) Event

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

func NewStreamStartEvent(encoding Encoding) Event

NewStreamStartEvent creates a new STREAM-START event.

func (*Event) Delete

func (e *Event) Delete()

Delete an event object.

func (*Event) GetEncoding

func (e *Event) GetEncoding() Encoding

GetEncoding returns the stream encoding (for STREAM_START_EVENT).

func (*Event) GetQuotedImplicit

func (e *Event) GetQuotedImplicit() bool

GetQuotedImplicit reports whether a scalar tag may be omitted for a non-plain scalar style.

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 EventReader

type EventReader struct {
	// contains filtered or unexported fields
}

EventReader reads native or plugin events using the same loading options. Plugin input is buffered on the first Parse call.

func NewEventReader

func NewEventReader(r io.Reader, opts *Options) *EventReader

NewEventReader creates an event reader for the configured input pipeline.

func (*EventReader) Delete

func (e *EventReader) Delete()

Delete releases buffered input and native parser resources.

func (*EventReader) Parse

func (e *EventReader) Parse(event *Event) error

Parse returns the next event, or io.EOF after the stream end.

type EventType

type EventType int8

EventType represents the type of a parsing or emitting event.

const (
	// NO_EVENT represents an empty event.
	NO_EVENT EventType = iota
	// STREAM_START_EVENT represents a STREAM-START event.
	STREAM_START_EVENT
	// STREAM_END_EVENT represents a STREAM-END event.
	STREAM_END_EVENT
	// DOCUMENT_START_EVENT represents a DOCUMENT-START event.
	DOCUMENT_START_EVENT
	// DOCUMENT_END_EVENT represents a DOCUMENT-END event.
	DOCUMENT_END_EVENT
	// ALIAS_EVENT represents an ALIAS event.
	ALIAS_EVENT
	// SCALAR_EVENT represents a SCALAR event.
	SCALAR_EVENT
	// SEQUENCE_START_EVENT represents a SEQUENCE-START event.
	SEQUENCE_START_EVENT
	// SEQUENCE_END_EVENT represents a SEQUENCE-END event.
	SEQUENCE_END_EVENT
	// MAPPING_START_EVENT represents a MAPPING-START event.
	MAPPING_START_EVENT
	// MAPPING_END_EVENT represents a MAPPING-END event.
	MAPPING_END_EVENT
	// TAIL_COMMENT_EVENT represents a TAIL-COMMENT event.
	TAIL_COMMENT_EVENT
)

Event types.

func (EventType) String

func (e EventType) String() string

String returns a string representation of the event type.

type FromYAMLNode

type FromYAMLNode interface {
	FromYAMLNode(*Node) error
}

FromYAMLNode is a reserved internal interface. The current loading pipeline does not invoke it. Use Unmarshaler to customize loading.

type IndentConfig

type IndentConfig struct {
	Mode      IndentMode
	LoadStyle IndentStyle
	DumpStyle IndentStyle
	Scope     IndentScope
}

IndentConfig configures tab-indentation loading and dumping.

func (IndentConfig) Normalize

func (c IndentConfig) Normalize() (IndentConfig, error)

Normalize fills defaults and validates a tab-indentation configuration.

type IndentMode

type IndentMode string

IndentMode supplies loading and dumping defaults.

const (
	IndentModeAuto IndentMode = "auto"
	IndentModeTabs IndentMode = "tabs"
)

type IndentScope

type IndentScope string

IndentScope controls how long an auto-detected style remains active.

const (
	IndentScopeDocument IndentScope = "document"
	IndentScopeStream   IndentScope = "stream"
)

type IndentStyle

type IndentStyle string

IndentStyle identifies the characters used for structural indentation.

const (
	IndentStyleAuto   IndentStyle = "auto"
	IndentStyleSpaces IndentStyle = "spaces"
	IndentStyleTabs   IndentStyle = "tabs"
)

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 Kind

type Kind uint32

Kind represents the type of YAML Node.Kind.

const (
	// DocumentNode represents the root of a YAML document.
	DocumentNode Kind = 1 << iota
	// SequenceNode represents a YAML sequence (list).
	SequenceNode
	// MappingNode represents a YAML mapping (dictionary).
	MappingNode
	// ScalarNode represents a YAML scalar value.
	ScalarNode
	// AliasNode represents a reference to an anchored node.
	AliasNode
	// StreamNode represents a container for multiple YAML documents.
	StreamNode
)

Kind constants define the different types of YAML Node.

type LineBreak

type LineBreak int

LineBreak represents the line break style used in YAML output.

const (
	// ANY_BREAK lets the parser choose the break type.
	ANY_BREAK LineBreak = iota

	// CR_BREAK uses CR for line breaks (Mac style).
	CR_BREAK
	// LN_BREAK uses LN for line breaks (Unix style).
	LN_BREAK
	// CRLN_BREAK uses CR LN for line breaks (DOS style).
	CRLN_BREAK
)

Possible LineBreak values.

type LoadError

type LoadError struct {
	// Stage identifies the processing stage where the error occurred.
	Stage Stage
	// Message provides a description of the error.
	Message string

	// Mark is the primary position in the input where the error occurred.
	Mark Mark
	// ContextMark is an optional context position (e.g., start of construct)
	ContextMark Mark
	// ContextMsg is an optional message describing the context of the error.
	ContextMsg string
	// 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

func NewLoadError(stage Stage, message string, mark Mark, cause error) *LoadError

NewLoadError creates a LoadError with an underlying cause. The cause is accessible via Unwrap for use with errors.Is and errors.As.

func (*LoadError) Error

func (e *LoadError) Error() string

Error returns the error message with stage and position information. If a formatter is set (via the error-format plugin), it is called instead. Default format: "go-yaml load error in <stage> at L:C: <message>" Or with context: "go-yaml load error in <stage> (<ctx>) at L:C-L:C: <message>"

func (*LoadError) Unwrap

func (e *LoadError) Unwrap() error

Unwrap returns the underlying error.

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.

func (*LoadErrors) Is

func (e *LoadErrors) Is(target error) bool

Is implements errors.Is for Go versions prior to 1.20 that don't support the Unwrap() []error interface. It checks if any wrapped error matches the target error.

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

func NewLoader(r io.Reader, opts ...Option) (*Loader, error)

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) Load

func (l *Loader) Load(v any) (err error)

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 the 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) SetLegacyLoaderKnownFields

func (l *Loader) SetLegacyLoaderKnownFields(enable bool)

SetLegacyLoaderKnownFields allows changing the known fields setting from the legacy Decoder API.

This method is only provided for backward compatibility with the legacy Decoder API. Do not use in libyaml, use WithKnownFields instead.

type MappingStyle

type MappingStyle styleInt

MappingStyle represents the formatting style of a mapping node.

const (
	// ANY_MAPPING_STYLE lets the emitter choose the style.
	ANY_MAPPING_STYLE MappingStyle = iota

	// BLOCK_MAPPING_STYLE represents a block mapping style.
	BLOCK_MAPPING_STYLE
	// FLOW_MAPPING_STYLE represents a flow mapping style.
	FLOW_MAPPING_STYLE
)

Possible MappingStyle values.

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.

func (Mark) RangeString added in v0.2.0

func (m Mark) RangeString(end Mark) string

RangeString is the exported form of rangeString for use by plugins.

func (Mark) ShortString added in v0.2.0

func (m Mark) ShortString() string

ShortString is the exported form of shortString for use by plugins.

func (Mark) String

func (m Mark) String() string

String returns a human-readable string representation of the position mark.

type Marshaler

type Marshaler interface {
	MarshalYAML() (any, error)
}

Marshaler interface may be implemented by types to customize their behavior when being marshaled into a YAML document.

type MergeKeyConfig added in v0.2.0

type MergeKeyConfig = mergekey.Config

MergeKeyConfig configures merge-key recognition and conflict handling.

type MergeKeyInput added in v0.2.0

type MergeKeyInput struct {
	Target  *Node
	Sources []*Node
	Key     func(*Node) (any, error)
}

MergeKeyInput contains read-only effective mappings in precedence order. Target has no merge directives. Sources have already had aliases and nested merges expanded. Key constructs a comparable destination-aware key. Unconstructible keys are reported as *LoadErrors; conversion diagnostics, if any, are retained by the constructor. Algorithms can skip those entries. The input and callback are valid only for the duration of MergeMappings.

type MergeKeyPlugin added in v0.2.0

type MergeKeyPlugin interface {
	MergeKeyConfig() MergeKeyConfig
	MergeMappings(MergeKeyInput) (*Node, error)
}

MergeKeyPlugin chooses the effective mapping before value construction. Implementations must support independent concurrent calls, leave input graphs unchanged, and return a MappingNode with paired key/value children.

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 ComposeEvents

func ComposeEvents(events []Event, opts *Options) (nodes []*Node, err error)

ComposeEvents resolves an event stream into document nodes.

func (*Node) Decode

func (n *Node) Decode(v any) (err error)

Decode decodes the node and stores its data into the value pointed to by v.

See the documentation for yaml.Unmarshal for details about the conversion of YAML into a Go value.

func (*Node) Dump

func (n *Node) Dump(v any, opts ...Option) (err error)

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. Node stores styles, but not output indentation or document-marker settings. Apply those options again when serializing the node to YAML.

See the documentation for yaml.Marshal for details about the conversion of Go values into YAML.

func (*Node) Encode

func (n *Node) Encode(v any) (err error)

Encode encodes value v and stores its representation in n.

See the documentation for yaml.Marshal for details about the conversion of Go values into YAML.

func (*Node) IsZero

func (n *Node) IsZero() bool

IsZero returns whether the node has all of its fields unset.

func (*Node) Load

func (n *Node) Load(v any, opts ...Option) (err error)

Load decodes the node and stores its data into the value pointed to by v, applying the given options. Explicit Alias-Data policies are rejected because composition has already occurred and the policy cannot be applied to this node graph.

Each call starts with fresh options, independently of an outer Loader. Pass WithKnownFields() explicitly to check fields inside a custom UnmarshalYAML implementation. Parser settings do not apply to this already composed graph.

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

func (n *Node) LongTag() string

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.

func (*Node) SetString

func (n *Node) SetString(s string)

SetString is a convenience function that sets the node to a string value and defines its style in a pleasant way depending on its content.

func (*Node) ShortTag

func (n *Node) ShortTag() string

ShortTag returns the short form of the YAML tag that indicates data type for the node. If the Tag field isn't explicitly defined, one will be computed based on the node properties.

type Option

type Option func(*Options) error

Option allows configuring YAML loading and dumping operations.

func CombineOptions

func CombineOptions(opts ...Option) Option

CombineOptions combines multiple options into a single Option. This is useful for creating option presets or combining version defaults with custom options.

func WithAllDocuments

func WithAllDocuments(all ...bool) Option

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

func WithCanonical(canonical ...bool) Option

WithCanonical selects the emitter's canonical YAML layout.

It emits explicit document starts, flow collections, and quoted scalars. Tags still depend on the node graph and desolver; this option alone does not force an explicit tag on every value. Scalar types may change when reloading canonical output. When called without arguments, defaults to true.

The default is false.

func WithCompactSeqIndent

func WithCompactSeqIndent(compact ...bool) Option

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

func WithExplicitEnd(explicit ...bool) Option

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

func WithExplicitStart(explicit ...bool) Option

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

func WithFlowSimpleCollections(flow ...bool) Option

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

func WithIndent(indent int) Option

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

func WithKnownFields(knownFields ...bool) Option

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. Calling WithKnownFields() enables checking; it is disabled by default.

func WithLineBreak

func WithLineBreak(lineBreak LineBreak) Option

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

func WithLineWidth(width int) Option

WithLineWidth sets the preferred line width for YAML output.

The emitter attempts to wrap long scalars without changing their value. Long words may exceed this width. 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

func WithSingleDocument(singleDocument ...bool) Option

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 ignores later documents, including their syntax errors. Omit this option with Load to require exactly one document.

func WithStreamNodes

func WithStreamNodes(enable ...bool) Option

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

func WithUnicode(unicode ...bool) Option

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\xE9"). When called without arguments, defaults to true.

The default is true.

func WithUniqueKeys

func WithUniqueKeys(uniqueKeys ...bool) Option

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 {

	// KnownFields enforces strict field checking when loading into structs.
	KnownFields bool
	// SingleDocument controls whether only the first document is loaded from a stream.
	SingleDocument bool
	// UniqueKeys enforces that mapping keys are unique when loading.
	UniqueKeys bool
	// StreamNodes enables returning stream boundary nodes when loading YAML.
	StreamNodes bool
	// AllDocuments enables multi-document mode for [Load] and [Dump] operations.
	AllDocuments bool

	// Dumping options
	// Indent sets the number of spaces to use for indentation when dumping YAML content (2-9).
	Indent int
	// CompactSeqIndent controls whether the sequence indicator '- ' is considered part of the indentation.
	CompactSeqIndent bool
	// LineWidth sets the preferred line width for YAML output (-1 for unlimited).
	LineWidth int
	// Unicode controls whether non-ASCII characters are allowed in YAML output.
	Unicode bool
	// Canonical forces canonical YAML output format (explicit tags for all values).
	Canonical bool
	// LineBreak sets the line ending style for YAML output (LN, CR, CRLF).
	LineBreak LineBreak
	// ExplicitStart controls whether document start markers (---) are always emitted.
	ExplicitStart bool
	// ExplicitEnd controls whether document end markers (...) are always emitted.
	ExplicitEnd bool
	// FlowSimpleCollections controls whether simple collections use flow style.
	FlowSimpleCollections bool
	// QuotePreference sets the preferred quote style for strings that require quoting.
	QuotePreference QuoteStyle

	// Parser supplies complete events in place of native parsing.
	Parser ParserPlugin

	// MergeKey selects the mapping merge algorithm.
	MergeKey MergeKeyPlugin

	// AliasData supplies per-stream anchor policy. Nil selects ordinary
	// document-scoped anchors, rather than disabling aliases.
	AliasData AliasDataPlugin

	// IndentConfig enables tab-aware structural indentation.
	IndentConfig *IndentConfig

	// Error formatting (set by WithPlugin with an error-format plugin).
	FormatLoadError func(*LoadError) string
	FormatDumpError func(*DumpError) string

	// Loader limit checks (set by ApplyOptions or a loader-limits plugin).
	// DepthCheck is called to verify the current nesting depth.
	DepthCheck func(depth int, ctx *DepthContext) error
	// AliasCheck is called to verify the number of aliases relative to constructs.
	AliasCheck func(aliasCount, constructCount int) error
	// contains filtered or unexported fields
}

Options holds configuration for both loading and dumping YAML.

func ApplyOptions

func ApplyOptions(opts ...Option) (*Options, error)

ApplyOptions applies the given options to a new options struct. Starts with v4 defaults.

type Parser

type Parser struct {

	// HeadComment is the current head comments.
	HeadComment []byte
	// LineComment is the current line comments.
	LineComment []byte
	// FootComment is the current foot comments.
	FootComment []byte
	// contains filtered or unexported fields
}

Parser structure holds all information about the current state of the parser.

func NewParser

func NewParser() Parser

NewParser creates a new parser object.

func (*Parser) Delete

func (parser *Parser) Delete()

Delete a parser object.

func (*Parser) GetCommentsHead

func (parser *Parser) GetCommentsHead() int

GetCommentsHead returns the current position in the comment queue.

func (*Parser) GetPendingComments

func (parser *Parser) GetPendingComments() []Comment

GetPendingComments returns the parser's comment queue for CLI access.

func (*Parser) Parse

func (parser *Parser) Parse(event *Event) error

Parse gets the next event.

func (*Parser) Scan

func (parser *Parser) Scan(token *Token) error

Scan advances the buffer pointer and reads the next token.

func (*Parser) SetEncoding

func (parser *Parser) SetEncoding(encoding Encoding)

SetEncoding sets the source encoding.

func (*Parser) SetIndentConfig

func (parser *Parser) SetIndentConfig(config *IndentConfig)

SetIndentConfig configures tab-aware indentation scanning.

func (*Parser) SetInputEvents

func (parser *Parser) SetInputEvents(events []Event)

SetInputEvents sets a pre-parsed event stream. It is intended for internal pipeline tooling that needs to resume processing at the composer stage.

func (*Parser) SetInputReader

func (parser *Parser) SetInputReader(r io.Reader)

SetInputReader sets a file input.

func (*Parser) SetInputString

func (parser *Parser) SetInputString(input []byte)

SetInputString sets a string input.

func (*Parser) SetInputTokens

func (parser *Parser) SetInputTokens(tokens []Token, comments []Comment)

SetInputTokens sets a pre-tokenized input stream. It is intended for internal pipeline tooling that needs to resume processing at the parser stage.

func (*Parser) SetSkipComments

func (parser *Parser) SetSkipComments(skip bool)

SetSkipComments enables or disables comment scanning. When enabled, the scanner skips comment tokens for better performance.

func (*Parser) UnfoldComments

func (parser *Parser) UnfoldComments(token *Token)

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 ParserPlugin

type ParserPlugin interface {
	Parse(input []byte) ([]PluginEvent, error)
}

ParserPlugin supplies a complete event stream for a load operation. Parse returns a complete stream, including stream and document boundaries. Implementations must support concurrent calls with independent input.

type ParserState

type ParserState int

ParserState represents the state of the parser.

const (
	// PARSE_STREAM_START_STATE expects STREAM-START.
	PARSE_STREAM_START_STATE ParserState = iota

	// PARSE_IMPLICIT_DOCUMENT_START_STATE expects the beginning of an implicit document.
	PARSE_IMPLICIT_DOCUMENT_START_STATE
	// PARSE_DOCUMENT_START_STATE expects DOCUMENT-START.
	PARSE_DOCUMENT_START_STATE
	// PARSE_DOCUMENT_CONTENT_STATE expects the content of a document.
	PARSE_DOCUMENT_CONTENT_STATE
	// PARSE_DOCUMENT_END_STATE expects DOCUMENT-END.
	PARSE_DOCUMENT_END_STATE
	// PARSE_BLOCK_NODE_STATE expects a block node.
	PARSE_BLOCK_NODE_STATE
	// PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE expects the first entry of a block sequence.
	PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE
	// PARSE_BLOCK_SEQUENCE_ENTRY_STATE expects an entry of a block sequence.
	PARSE_BLOCK_SEQUENCE_ENTRY_STATE
	// PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE expects an entry of an indentless sequence.
	PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE
	// PARSE_BLOCK_MAPPING_FIRST_KEY_STATE expects the first key of a block mapping.
	PARSE_BLOCK_MAPPING_FIRST_KEY_STATE
	// PARSE_BLOCK_MAPPING_KEY_STATE expects a block mapping key.
	PARSE_BLOCK_MAPPING_KEY_STATE
	// PARSE_BLOCK_MAPPING_VALUE_STATE expects a block mapping value.
	PARSE_BLOCK_MAPPING_VALUE_STATE
	// PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE expects the first entry of a flow sequence.
	PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE
	// PARSE_FLOW_SEQUENCE_ENTRY_STATE expects an entry of a flow sequence.
	PARSE_FLOW_SEQUENCE_ENTRY_STATE
	// PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE expects a key of an ordered mapping.
	PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE
	// PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE expects a value of an ordered mapping.
	PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE
	// PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE expects the and of an ordered mapping entry.
	PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE
	// PARSE_FLOW_MAPPING_FIRST_KEY_STATE expects the first key of a flow mapping.
	PARSE_FLOW_MAPPING_FIRST_KEY_STATE
	// PARSE_FLOW_MAPPING_KEY_STATE expects a key of a flow mapping.
	PARSE_FLOW_MAPPING_KEY_STATE
	// PARSE_FLOW_MAPPING_VALUE_STATE expects a value of a flow mapping.
	PARSE_FLOW_MAPPING_VALUE_STATE
	// PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE expects an empty value of a flow mapping.
	PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE
	// PARSE_END_STATE expects nothing.
	PARSE_END_STATE
)

Possible ParserState constants are 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 PluginEvent

type PluginEvent struct {
	Type               string
	Value, Anchor, Tag string
	Style              string
	Flow, Explicit     bool
	StartMark, EndMark Mark
	Version            *StreamVersionDirective
	TagDirectives      []StreamTagDirective
	HeadComment        string
	LineComment        string
	FootComment        string
}

PluginEvent is a portable YAML event supplied by a plugin. Type is stream_start, stream_end, document_start, document_end, mapping_start, mapping_end, sequence_start, sequence_end, scalar, or alias. Style is empty (plain), single, double, literal, or folded for scalars. Alias events use Anchor for the referenced name. Tags are resolved URIs or local tags; an empty tag requests resolution. Positions are one-based, with zero meaning unknown.

type QuoteStyle

type QuoteStyle int

QuoteStyle represents the preferred quote style for scalar values.

const (
	// QuoteSingle prefers single quotes for scalar values.
	QuoteSingle QuoteStyle = iota
	// QuoteDouble prefers double quotes for scalar values.
	QuoteDouble
	// QuoteLegacy uses double quotes in the representer and single quotes in the emitter.
	QuoteLegacy
)

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

type ReadHandler func(parser *Parser, buffer []byte) (n int, err error)

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.

func (*Representer) Represent

func (r *Representer) Represent(tag string, in reflect.Value) *Node

Represent converts a Go value to a YAML node tree. This is the primary method for the Representer stage in the dump pipeline.

Nodes found in the value (*Node or Node) are used as-is rather than copied, so the returned tree may share nodes with the caller, and later stages must not modify it.

type Resolver

type Resolver struct {
	// contains filtered or unexported fields
}

Resolver handles tag resolution for YAML nodes.

func NewResolver

func NewResolver(opts *Options) *Resolver

NewResolver creates a new Resolver with the given options.

func (*Resolver) Resolve

func (r *Resolver) Resolve(n *Node)

Resolve walks the node tree and resolves tags for untagged nodes. This is called after composition to: - Default quoted scalars to !!str - Default sequences to !!seq - Default mappings to !!map - Resolve plain scalars to implicit types (int, float, bool, null, timestamp)

type ScalarConstructFunc

type ScalarConstructFunc func(c *Constructor, n *Node, resolved any, out reflect.Value) bool

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 (
	// ANY_SCALAR_STYLE lets the emitter choose the style.
	ANY_SCALAR_STYLE ScalarStyle = 0

	// PLAIN_SCALAR_STYLE represents the plain scalar style.
	PLAIN_SCALAR_STYLE ScalarStyle = 1 << iota
	// SINGLE_QUOTED_SCALAR_STYLE represents the single-quoted scalar style.
	SINGLE_QUOTED_SCALAR_STYLE
	// DOUBLE_QUOTED_SCALAR_STYLE represents the double-quoted scalar style.
	DOUBLE_QUOTED_SCALAR_STYLE
	// LITERAL_SCALAR_STYLE represents the literal scalar style.
	LITERAL_SCALAR_STYLE
	// FOLDED_SCALAR_STYLE represents the folded scalar style.
	FOLDED_SCALAR_STYLE
)

Possible ScalarStyle values.

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 (
	// ANY_SEQUENCE_STYLE lets the emitter choose the style.
	ANY_SEQUENCE_STYLE SequenceStyle = iota

	// BLOCK_SEQUENCE_STYLE represents a block sequence style.
	BLOCK_SEQUENCE_STYLE
	// FLOW_SEQUENCE_STYLE represents a flow sequence style.
	FLOW_SEQUENCE_STYLE
)

Possible SequenceStyle values.

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.

Inferable tags are removed from the emitted events by the Desolver, not from the tree: Serialize only reads node and its descendants.

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

type StreamTagDirective struct {
	Handle string
	Prefix string
}

StreamTagDirective represents a YAML %TAG directive for Stream.TagDirectives.

type StreamVersionDirective

type StreamVersionDirective struct {
	Major int
	Minor int
}

StreamVersionDirective represents a YAML %YAML version directive for Stream.Version.

type Style

type Style uint32

Style represents the formatting style of a YAML Node (see Node.Style)

const (
	// TaggedStyle explicitly shows the tag on the node.
	TaggedStyle Style = 1 << iota
	// DoubleQuotedStyle uses double quotes for scalar values.
	DoubleQuotedStyle
	// SingleQuotedStyle uses single quotes for scalar values.
	SingleQuotedStyle
	// LiteralStyle uses literal block scalar style (|).
	LiteralStyle
	// FoldedStyle uses folded block scalar style (>).
	FoldedStyle
	// FlowStyle uses flow style (inline) formatting.
	FlowStyle
)

Style constants define different formatting styles for YAML Node.

type TabIndentPlugin

type TabIndentPlugin interface {
	TabIndentConfig() IndentConfig
}

TabIndentPlugin enables tab-aware structural indentation.

type TagDirective

type TagDirective struct {
	// contains filtered or unexported fields
}

TagDirective holds the YAML tag directive data.

func NewTagDirective

func NewTagDirective(handle, prefix string) TagDirective

NewTagDirective creates 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

type ToYAMLNode interface {
	ToYAMLNode() (*Node, error)
}

ToYAMLNode is a reserved internal interface. The current dumping pipeline does not invoke it. Use Marshaler to customize dumping.

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.

func (*Token) GetEncoding

func (t *Token) GetEncoding() Encoding

GetEncoding returns the stream encoding carried by a STREAM-START token.

func (*Token) GetPrefix

func (t *Token) GetPrefix() string

GetPrefix returns the prefix carried by a TAG-DIRECTIVE token.

func (*Token) GetSuffix

func (t *Token) GetSuffix() string

GetSuffix returns the suffix carried by a TAG token.

func (*Token) GetVersion

func (t *Token) GetVersion() (int, int)

GetVersion returns the version carried by a VERSION-DIRECTIVE token.

func (*Token) SetEncoding

func (t *Token) SetEncoding(encoding Encoding)

SetEncoding sets the stream encoding carried by a STREAM-START token.

func (*Token) SetPrefix

func (t *Token) SetPrefix(prefix string)

SetPrefix sets the prefix carried by a TAG-DIRECTIVE token.

func (*Token) SetSuffix

func (t *Token) SetSuffix(suffix string)

SetSuffix sets the suffix carried by a TAG token.

func (*Token) SetVersion

func (t *Token) SetVersion(major, minor int)

SetVersion sets the version carried by a VERSION-DIRECTIVE token.

type TokenType

type TokenType int

TokenType represents the Token.Type of a scanned Token.

const (
	// NO_TOKEN represents an empty token.
	NO_TOKEN TokenType = iota

	// STREAM_START_TOKEN represents a STREAM-START token.
	STREAM_START_TOKEN
	// STREAM_END_TOKEN represents a STREAM-END token.
	STREAM_END_TOKEN
	// VERSION_DIRECTIVE_TOKEN represents a VERSION-DIRECTIVE token.
	VERSION_DIRECTIVE_TOKEN

	// TAG_DIRECTIVE_TOKEN represents a TAG-DIRECTIVE token.
	TAG_DIRECTIVE_TOKEN
	// DOCUMENT_START_TOKEN represents a DOCUMENT-START token.
	DOCUMENT_START_TOKEN
	// DOCUMENT_END_TOKEN represents a DOCUMENT-END token.
	DOCUMENT_END_TOKEN

	// BLOCK_SEQUENCE_START_TOKEN represents a BLOCK-SEQUENCE-START token.
	BLOCK_SEQUENCE_START_TOKEN
	// BLOCK_MAPPING_START_TOKEN represents a BLOCK-MAPPING-START token.
	BLOCK_MAPPING_START_TOKEN
	// BLOCK_END_TOKEN represents a BLOCK-END token.
	BLOCK_END_TOKEN

	// FLOW_SEQUENCE_START_TOKEN represents a FLOW-SEQUENCE-START token.
	FLOW_SEQUENCE_START_TOKEN
	// FLOW_SEQUENCE_END_TOKEN represents a FLOW-SEQUENCE-END token.
	FLOW_SEQUENCE_END_TOKEN
	// FLOW_MAPPING_START_TOKEN represents a FLOW-MAPPING-START token.
	FLOW_MAPPING_START_TOKEN
	// FLOW_MAPPING_END_TOKEN represents a FLOW-MAPPING-END token.
	FLOW_MAPPING_END_TOKEN

	// BLOCK_ENTRY_TOKEN represents a BLOCK-ENTRY token.
	BLOCK_ENTRY_TOKEN
	// FLOW_ENTRY_TOKEN represents a FLOW-ENTRY token.
	FLOW_ENTRY_TOKEN
	// KEY_TOKEN represents a KEY token.
	KEY_TOKEN
	// VALUE_TOKEN represents a VALUE token.
	VALUE_TOKEN

	// ALIAS_TOKEN represents an ALIAS token.
	ALIAS_TOKEN
	// ANCHOR_TOKEN represents an ANCHOR token.
	ANCHOR_TOKEN
	// TAG_TOKEN represents a TAG token.
	TAG_TOKEN
	// SCALAR_TOKEN represents a SCALAR token.
	SCALAR_TOKEN
	// COMMENT_TOKEN represents a COMMENT token.
	COMMENT_TOKEN
)

Possible TokenType values.

func (TokenType) String

func (tt TokenType) String() string

String returns a string representation of the token type.

type TypeError deprecated

type TypeError struct {
	Errors []string
}

TypeError is a legacy error type retained for compatibility.

Load and Loader.Load return *LoadErrors when one or more fields cannot be decoded into the requested types. The destination value may be partially populated. For compatibility, LoadErrors.As synthesizes a *TypeError when callers use errors.As.

Deprecated: Use LoadErrors instead.

func (*TypeError) Error

func (e *TypeError) Error() string

Error returns a formatted error message listing all unmarshal errors.

type Unmarshaler

type Unmarshaler interface {
	UnmarshalYAML(node *Node) error
}

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 NewVersionDirective

func NewVersionDirective(major, minor int) *VersionDirective

NewVersionDirective creates 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

type WriteHandler func(emitter *Emitter, buffer []byte) error

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) Error

func (e WriterError) Error() string

Error returns the error message.

func (WriterError) Unwrap

func (e WriterError) Unwrap() error

Unwrap returns the underlying error.

type YAMLError

type YAMLError struct {
	Err error
}

YAMLError is an internal error wrapper type.

func (*YAMLError) Error

func (e *YAMLError) Error() string

Error returns the error message.

Jump to

Keyboard shortcuts

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