Debian Codegraph @

yaml.go

raw symbols SCIP
1 // Copyright 2011-2019 Canonical Ltd
2 // Copyright 2025 The go-yaml Project Contributors
3 // SPDX-License-Identifier: Apache-2.0
4
5 // Package yaml implements YAML support for the Go language.
6 //
7 // Source code and other details for the project are available at GitHub:
8 //
9 // https://github.com/yaml/go-yaml
10 //
11 // This file contains:
12 // - Version preset functions (WithV2Defaults, WithV3Defaults, WithV4Defaults)
13 // - Options API (WithIndent, WithKnownFields, etc.)
14 // - Type and constant re-exports from internal/libyaml
15 // - Helper functions for struct field handling
16 // - Load/Dump API (Load, Dump, Loader, Dumper)
17 // - Classic APIs (Decoder, Encoder, Unmarshal, Marshal)
18
19 package yaml
20
21 import (
22 "errors"
23 "fmt"
24 "io"
25
26 "go.yaml.in/yaml/v4/internal/libyaml"
27 "go.yaml.in/yaml/v4/plugin/limit"
28 )
29
30 //-----------------------------------------------------------------------------
31 // Version presets
32 //-----------------------------------------------------------------------------
33
34 // Usage:
35 // yaml.Dump(&data, yaml.WithV3Defaults())
36 // yaml.Dump(&data, yaml.WithV3Defaults(), yaml.WithIndent(2), yaml.WithCompactSeqIndent())
37
38 // WithV2Defaults returns V2-compatible default options.
39 func WithV2Defaults() Option {
40 return Options(
41 WithIndent(2),
42 WithCompactSeqIndent(false),
43 WithLineWidth(80),
44 WithUnicode(true),
45 WithUniqueKeys(true),
46 WithQuotePreference(QuoteLegacy),
47 WithPlugin(limit.New()),
48 )
49 }
50
51 // WithV3Defaults returns V3-compatible default options.
52 func WithV3Defaults() Option {
53 return Options(
54 WithIndent(4),
55 WithCompactSeqIndent(false),
56 WithLineWidth(80),
57 WithUnicode(true),
58 WithUniqueKeys(true),
59 WithQuotePreference(QuoteLegacy),
60 WithPlugin(limit.New()),
61 )
62 }
63
64 // WithV4Defaults returns the current V4 default options.
65 func WithV4Defaults() Option {
66 return Options(
67 WithIndent(2),
68 WithCompactSeqIndent(true),
69 WithLineWidth(80),
70 WithUnicode(true),
71 WithUniqueKeys(true),
72 WithQuotePreference(QuoteSingle),
73 WithPlugin(limit.New()),
74 )
75 }
76
77 //-----------------------------------------------------------------------------
78 // Options
79 //-----------------------------------------------------------------------------
80
81 // Option allows configuring YAML loading and dumping operations.
82 type Option = libyaml.Option
83
84 // Option configuration functions
85 var (
86 // WithIndent sets the number of spaces to use for indentation when
87 // dumping YAML content.
88 //
89 // Valid values are 2-9. Common choices: 2 (compact), 4 (readable).
90 WithIndent = libyaml.WithIndent
91
92 // WithCompactSeqIndent configures whether the sequence indicator '- ' is
93 // considered part of the indentation when dumping YAML content.
94 //
95 // If compact is true, '- ' is treated as part of the indentation.
96 // If compact is false, '- ' is not treated as part of the indentation.
97 // When called without arguments, defaults to true.
98 WithCompactSeqIndent = libyaml.WithCompactSeqIndent
99
100 // WithKnownFields enables or disables strict field checking during YAML
101 // loading.
102 //
103 // When enabled, loading will return an error if the YAML input contains
104 // fields that do not correspond to any fields in the target struct.
105 // When called without arguments, defaults to true.
106 WithKnownFields = libyaml.WithKnownFields
107
108 // WithSingleDocument configures the Loader to only process the first
109 // document in a YAML stream. After the first document is loaded,
110 // subsequent calls to Load will return [io.EOF].
111 //
112 // When called without arguments, defaults to true.
113 //
114 // This is useful when you expect exactly one document and want behavior
115 // similar to Unmarshal.
116 WithSingleDocument = libyaml.WithSingleDocument
117
118 // WithStreamNodes enables returning stream boundary nodes when loading
119 // YAML.
120 //
121 // When enabled, Loader.Load returns an interleaved sequence of
122 // StreamNode and DocumentNode values:
123 //
124 // [StreamNode, DocNode, StreamNode, DocNode, ..., StreamNode]
125 //
126 // StreamNodes contain metadata about the stream including:
127 // - Encoding (UTF-8, UTF-16LE, UTF-16BE)
128 // - YAML version directive (%YAML)
129 // - Tag directives (%TAG)
130 // - Position information (Line, Column)
131 //
132 // An empty YAML stream returns a single StreamNode.
133 // When called without arguments, defaults to true.
134 //
135 // The default is false.
136 WithStreamNodes = libyaml.WithStreamNodes
137
138 // WithAllDocuments enables multi-document mode for Load and Dump
139 // operations.
140 //
141 // When used with Load, the target must be a pointer to a slice.
142 // All documents in the YAML stream will be decoded into the slice.
143 // Zero documents results in an empty slice (no error).
144 //
145 // When used with Dump, the input must be a slice.
146 // Each element will be encoded as a separate YAML document
147 // with "---" separators.
148 //
149 // When called without arguments, defaults to true.
150 //
151 // The default is false (single-document mode).
152 WithAllDocuments = libyaml.WithAllDocuments
153
154 // WithLineWidth sets the preferred line width for YAML output.
155 //
156 // When encoding long strings, the encoder will attempt to wrap them at
157 // this width using literal block style (|). Set to -1 or 0 for unlimited
158 // width.
159 //
160 // The default is 80 characters.
161 WithLineWidth = libyaml.WithLineWidth
162
163 // WithUnicode controls whether non-ASCII characters are allowed in YAML
164 // output.
165 //
166 // When true, non-ASCII characters appear as-is (e.g., "café").
167 // When false, non-ASCII characters are escaped (e.g., "caf\u00e9").
168 // When called without arguments, defaults to true.
169 //
170 // The default is true.
171 WithUnicode = libyaml.WithUnicode
172
173 // WithUniqueKeys enables or disables duplicate key detection during YAML
174 // loading.
175 //
176 // When enabled, loading will return an error if the YAML input contains
177 // duplicate keys in any mapping. This is a security feature that prevents
178 // key override attacks.
179 // When called without arguments, defaults to true.
180 //
181 // The default is true.
182 WithUniqueKeys = libyaml.WithUniqueKeys
183
184 // WithCanonical forces canonical YAML output format.
185 //
186 // When enabled, the encoder outputs strictly canonical YAML with explicit
187 // tags for all values. This produces verbose output primarily useful for
188 // debugging and YAML spec compliance testing.
189 // When called without arguments, defaults to true.
190 //
191 // The default is false.
192 WithCanonical = libyaml.WithCanonical
193
194 // WithLineBreak sets the line ending style for YAML output.
195 //
196 // Available options:
197 // - LineBreakLN: Unix-style \n (default)
198 // - LineBreakCR: Old Mac-style \r
199 // - LineBreakCRLN: Windows-style \r\n
200 //
201 // The default is LineBreakLN.
202 WithLineBreak = libyaml.WithLineBreak
203
204 // WithExplicitStart controls whether document start markers (---) are
205 // always emitted.
206 //
207 // When true, every document begins with an explicit "---" marker.
208 // When false (default), the marker is omitted for the first document.
209 // When called without arguments, defaults to true.
210 WithExplicitStart = libyaml.WithExplicitStart
211
212 // WithExplicitEnd controls whether document end markers (...) are always
213 // emitted.
214 //
215 // When true, every document ends with an explicit "..." marker.
216 // When false (default), the marker is omitted.
217 // When called without arguments, defaults to true.
218 WithExplicitEnd = libyaml.WithExplicitEnd
219
220 // WithFlowSimpleCollections controls whether simple collections use flow
221 // style.
222 //
223 // When true, sequences and mappings containing only scalar values (no
224 // nested collections) are rendered in flow style if they fit within the
225 // line width.
226 // Example: {name: test, count: 42} or [a, b, c]
227 // When called without arguments, defaults to true.
228 //
229 // When false (default), all collections use block style.
230 WithFlowSimpleCollections = libyaml.WithFlowSimpleCollections
231
232 // WithQuotePreference sets the preferred quote style for strings that
233 // require quoting.
234 //
235 // This option only affects strings that require quoting per the YAML spec.
236 // Plain strings that don't need quoting remain unquoted regardless of this
237 // setting. Quoting is required for:
238 // - Strings that look like other YAML types (true, false, null, 123, etc.)
239 // - Strings with leading/trailing whitespace
240 // - Strings containing special YAML syntax characters
241 // - Empty strings in certain contexts
242 //
243 // Quote styles:
244 // - QuoteSingle: Use single quotes (v4 default)
245 // - QuoteDouble: Use double quotes
246 // - QuoteLegacy: Legacy v2/v3 behavior (mixed quoting)
247 WithQuotePreference = libyaml.WithQuotePreference
248 )
249
250 // Options combines multiple options into a single Option.
251 // This is useful for creating option presets or combining version defaults
252 // with custom options.
253 //
254 // Example:
255 //
256 // opts := yaml.Options(yaml.WithV4Defaults(), yaml.WithIndent(3))
257 // yaml.Dump(&data, opts)
258 func Options(opts ...Option) Option {
259 return libyaml.CombineOptions(opts...)
260 }
261
262 // DepthKind represents the type of nesting (flow or block).
263 type DepthKind = libyaml.DepthKind
264
265 // DepthKind constants for nesting depth checks.
266 const (
267 DepthKindFlow = libyaml.DepthKindFlow
268 DepthKindBlock = libyaml.DepthKindBlock
269 )
270
271 // DepthContext holds context about a nesting depth check.
272 type DepthContext = libyaml.DepthContext
273
274 // WithPlugin registers one or more plugins for YAML processing.
275 //
276 // Plugins extend the YAML library with custom processing logic.
277 // Each plugin implements one or more plugin interfaces.
278 // Currently supported plugin types:
279 // - LimitPlugin: Controls depth and alias expansion limits
280 //
281 // Example:
282 //
283 // import "go.yaml.in/yaml/v4/plugin/limit"
284 // loader := yaml.NewLoader(data, yaml.WithPlugin(limit.New(limit.AliasNone())))
285 //
286 // Plugins use public types and can be implemented by external packages.
287 func WithPlugin(plugins ...any) Option {
288 return func(o *libyaml.Options) error {
289 for _, p := range plugins {
290 registered := false
291 if lp, ok := p.(LimitPlugin); ok {
292 o.DepthCheck = lp.CheckDepth
293 o.AliasCheck = lp.CheckAlias
294 registered = true
295 }
296 // Future plugin types add cases here (non-exclusive if)
297 if !registered {
298 return fmt.Errorf("yaml: unsupported plugin type: %T", p)
299 }
300 }
301 return nil
302 }
303 }
304
305 // OptsYAML parses a YAML string containing option settings and returns
306 // an Option that can be combined with other options using Options().
307 //
308 // The YAML string can specify any of these fields:
309 // - indent (int)
310 // - compact-seq-indent (bool)
311 // - line-width (int)
312 // - unicode (bool)
313 // - canonical (bool)
314 // - line-break (string: ln, cr, crln)
315 // - explicit-start (bool)
316 // - explicit-end (bool)
317 // - flow-simple-coll (bool)
318 // - known-fields (bool)
319 // - single-document (bool)
320 // - unique-keys (bool)
321 // - plugin (map of plugin name to config)
322 //
323 // The plugin field configures plugins by name. Each key is a plugin
324 // name and the value is its configuration map (or null for defaults).
325 // Currently supported: "limit" with keys "depth" and "alias" (int
326 // or null to disable).
327 //
328 // Only fields specified in the YAML will override other options when
329 // combined. Unspecified fields won't affect other options.
330 //
331 // Example:
332 //
333 // opts, err := yaml.OptsYAML(`
334 // indent: 3
335 // known-fields: true
336 // plugin:
337 // limit:
338 // depth: 50
339 // `)
340 // yaml.Dump(&data, yaml.Options(V4, opts))
341 func OptsYAML(yamlStr string) (Option, error) {
342 var cfg struct {
343 Indent *int `yaml:"indent"`
344 CompactSeqIndent *bool `yaml:"compact-seq-indent"`
345 LineWidth *int `yaml:"line-width"`
346 Unicode *bool `yaml:"unicode"`
347 Canonical *bool `yaml:"canonical"`
348 LineBreak *string `yaml:"line-break"`
349 ExplicitStart *bool `yaml:"explicit-start"`
350 ExplicitEnd *bool `yaml:"explicit-end"`
351 FlowSimpleCollections *bool `yaml:"flow-simple-coll"`
352 KnownFields *bool `yaml:"known-fields"`
353 SingleDocument *bool `yaml:"single-document"`
354 UniqueKeys *bool `yaml:"unique-keys"`
355 Plugin map[string]any `yaml:"plugin"`
356 }
357 if err := Load([]byte(yamlStr), &cfg, WithKnownFields()); err != nil {
358 return nil, err
359 }
360
361 // Build options only for fields that were set
362 var optList []Option
363 if cfg.Indent != nil {
364 optList = append(optList, WithIndent(*cfg.Indent))
365 }
366 if cfg.CompactSeqIndent != nil {
367 optList = append(optList, WithCompactSeqIndent(*cfg.CompactSeqIndent))
368 }
369 if cfg.LineWidth != nil {
370 optList = append(optList, WithLineWidth(*cfg.LineWidth))
371 }
372 if cfg.Unicode != nil {
373 optList = append(optList, WithUnicode(*cfg.Unicode))
374 }
375 if cfg.ExplicitStart != nil {
376 optList = append(optList, WithExplicitStart(*cfg.ExplicitStart))
377 }
378 if cfg.ExplicitEnd != nil {
379 optList = append(optList, WithExplicitEnd(*cfg.ExplicitEnd))
380 }
381 if cfg.FlowSimpleCollections != nil {
382 optList = append(optList, WithFlowSimpleCollections(*cfg.FlowSimpleCollections))
383 }
384 if cfg.KnownFields != nil {
385 optList = append(optList, WithKnownFields(*cfg.KnownFields))
386 }
387 if cfg.SingleDocument != nil && *cfg.SingleDocument {
388 optList = append(optList, WithSingleDocument())
389 }
390 if cfg.UniqueKeys != nil {
391 optList = append(optList, WithUniqueKeys(*cfg.UniqueKeys))
392 }
393 if cfg.Canonical != nil {
394 optList = append(optList, WithCanonical(*cfg.Canonical))
395 }
396 if cfg.LineBreak != nil {
397 switch *cfg.LineBreak {
398 case "ln":
399 optList = append(optList, WithLineBreak(LineBreakLN))
400 case "cr":
401 optList = append(optList, WithLineBreak(LineBreakCR))
402 case "crln":
403 optList = append(optList, WithLineBreak(LineBreakCRLN))
404 default:
405 return nil, errors.New("yaml: invalid line-break value (use ln, cr, or crln)")
406 }
407 }
408
409 for name, val := range cfg.Plugin {
410 switch name {
411 case "limit":
412 var cfgMap map[string]any
413 switch v := val.(type) {
414 case nil:
415 cfgMap = map[string]any{}
416 case map[string]any:
417 cfgMap = v
418 default:
419 return nil, fmt.Errorf("yaml: plugin %q value must be a mapping or null", name)
420 }
421 p, err := limit.NewFromYAML(cfgMap)
422 if err != nil {
423 return nil, err
424 }
425 optList = append(optList, WithPlugin(p))
426 default:
427 return nil, fmt.Errorf("yaml: unknown plugin %q", name)
428 }
429 }
430
431 return Options(optList...), nil
432 }
433
434 //-----------------------------------------------------------------------------
435 // Type and constant re-exports
436 //-----------------------------------------------------------------------------
437
438 // Re-export stream-related types
439 type (
440 Stream = libyaml.Stream
441 VersionDirective = libyaml.StreamVersionDirective
442
443 // TagDirective represents a YAML %TAG directive for stream nodes.
444 TagDirective = libyaml.StreamTagDirective
445
446 // Encoding represents the character encoding of a YAML stream.
447 Encoding = libyaml.Encoding
448 )
449
450 // Encoding constants for YAML stream encoding
451 const (
452 // EncodingAny lets the parser choose the encoding.
453 EncodingAny = libyaml.ANY_ENCODING
454
455 // EncodingUTF8 is the default UTF-8 encoding.
456 EncodingUTF8 = libyaml.UTF8_ENCODING
457
458 // EncodingUTF16LE is UTF-16-LE encoding with BOM.
459 EncodingUTF16LE = libyaml.UTF16LE_ENCODING
460
461 // EncodingUTF16BE is UTF-16-BE encoding with BOM.
462 EncodingUTF16BE = libyaml.UTF16BE_ENCODING
463 )
464
465 // Stage identifies the processing stage where an error occurred during YAML
466 // loading or dumping.
467 type Stage = libyaml.Stage
468
469 // Stage constants for YAML processing pipeline.
470 const (
471 // Load stages
472 ReaderStage = libyaml.ReaderStage // Input reading and encoding
473 ScannerStage = libyaml.ScannerStage // Tokenization
474 ParserStage = libyaml.ParserStage // Event stream parsing
475 ComposerStage = libyaml.ComposerStage // Node tree construction
476 ResolverStage = libyaml.ResolverStage // Tag resolution
477 ConstructorStage = libyaml.ConstructorStage // Go value construction
478
479 // Dump stages
480 RepresenterStage = libyaml.RepresenterStage // Go value to Node tree
481 SerializerStage = libyaml.SerializerStage // Node tree to events
482 EmitterStage = libyaml.EmitterStage // Events to YAML bytes
483 WriterStage = libyaml.WriterStage // Output writing
484 )
485
486 // Mark represents a position in the YAML document.
487 type Mark = libyaml.Mark
488
489 // Error types for YAML loading and dumping
490 type (
491 // LoadError represents an error encountered while decoding a YAML document.
492 //
493 // It contains details about the location in the document where the error
494 // occurred, as well as the processing stage that generated it.
495 LoadError = libyaml.LoadError
496
497 // LoadErrors is returned when one or more fields cannot be properly decoded.
498 //
499 // It contains multiple *[LoadError] instances with details about each error.
500 LoadErrors = libyaml.LoadErrors
501
502 // DumpError represents an error that occurred while dumping a YAML document.
503 //
504 // It identifies the processing stage where the error occurred and provides
505 // an optional underlying cause via Unwrap.
506 DumpError = libyaml.DumpError
507
508 // TypeError is a legacy error type retained for compatibility.
509 //
510 // Deprecated: Use [LoadErrors] instead.
511 //
512 //nolint:staticcheck // we are using deprecated TypeError for compatibility
513 TypeError = libyaml.TypeError
514 )
515
516 // NewLoadError creates a LoadError with an underlying cause error.
517 // The cause is accessible via Unwrap for use with [errors.Is] and [errors.As].
518 var NewLoadError = libyaml.NewLoadError
519
520 // NewDumpError creates a DumpError with an underlying cause error.
521 // The cause is accessible via Unwrap for use with [errors.Is] and [errors.As].
522 var NewDumpError = libyaml.NewDumpError
523
524 // LineBreak represents the line ending style for YAML output.
525 type LineBreak = libyaml.LineBreak
526
527 // Line break constants for different platforms.
528 const (
529 LineBreakLN = libyaml.LN_BREAK // Unix-style \n (default)
530 LineBreakCR = libyaml.CR_BREAK // Old Mac-style \r
531 LineBreakCRLN = libyaml.CRLN_BREAK // Windows-style \r\n
532 )
533
534 // QuoteStyle represents the quote style to use when quoting is required.
535 type QuoteStyle = libyaml.QuoteStyle
536
537 // Quote style constants for required quoting.
538 const (
539 QuoteSingle = libyaml.QuoteSingle // Prefer single quotes (v4 default)
540 QuoteDouble = libyaml.QuoteDouble // Prefer double quotes
541 QuoteLegacy = libyaml.QuoteLegacy // Legacy v2/v3 behavior
542 )
543
544 //-----------------------------------------------------------------------------
545 // Load/Dump API
546 //-----------------------------------------------------------------------------
547
548 // Advanced streaming API types
549 type (
550 // Loader reads and loads YAML values from an input stream with
551 // configurable options.
552 Loader = libyaml.Loader
553
554 // Dumper writes YAML values to an output stream with configurable options.
555 Dumper = libyaml.Dumper
556 )
557
558 // NewLoader returns a new Loader that reads from r with the given options.
559 func NewLoader(r io.Reader, opts ...Option) (*Loader, error) {
560 return libyaml.NewLoader(r, opts...)
561 }
562
563 // NewDumper returns a new Dumper that writes to w with the given options.
564 func NewDumper(w io.Writer, opts ...Option) (*Dumper, error) {
565 return libyaml.NewDumper(w, opts...)
566 }
567
568 // Load loads YAML document(s) with the given options.
569 func Load(in []byte, out any, opts ...Option) error {
570 return libyaml.Load(in, out, opts...)
571 }
572
573 // Dump encodes a value to YAML with the given options.
574 func Dump(in any, opts ...Option) (out []byte, err error) {
575 return libyaml.Dump(in, opts...)
576 }
577
578 //-----------------------------------------------------------------------------
579 // Classic APIs
580 //-----------------------------------------------------------------------------
581
582 // A Decoder reads and decodes YAML values from an input stream.
583 type Decoder struct {
584 loader *Loader
585 }
586
587 // NewDecoder returns a new decoder that reads from r.
588 //
589 // The decoder introduces its own buffering and may read
590 // data from r beyond the YAML values requested.
591 func NewDecoder(r io.Reader) *Decoder {
592 // NewLoader won't return error with WithV3Defaults() and withFromLegacy
593 loader, _ := NewLoader(r, WithV3Defaults(), withFromLegacy())
594 return &Decoder{loader: loader}
595 }
596
597 // KnownFields ensures that the keys in decoded mappings to
598 // exist as fields in the struct being decoded into.
599 func (dec *Decoder) KnownFields(enable bool) {
600 dec.loader.SetKnownFields(enable)
601 }
602
603 // Decode reads the next YAML-encoded value from its input
604 // and stores it in the value pointed to by v.
605 //
606 // See the documentation for Unmarshal for details about the
607 // conversion of YAML into a Go value.
608 func (dec *Decoder) Decode(v any) error {
609 return dec.loader.Load(v)
610 }
611
612 // An Encoder writes YAML values to an output stream.
613 type Encoder struct {
614 dumper *Dumper
615 }
616
617 // NewEncoder returns a new encoder that writes to w.
618 // The Encoder should be closed after use to flush all data
619 // to w.
620 func NewEncoder(w io.Writer) *Encoder {
621 // NewDumper won't return an error when using WithV3Defaults()
622 dumper, _ := NewDumper(w, WithV3Defaults())
623 return &Encoder{dumper: dumper}
624 }
625
626 // Encode writes the YAML encoding of v to the stream.
627 // If multiple items are encoded to the stream, the
628 // second and subsequent document will be preceded
629 // with a "---" document separator, but the first will not.
630 //
631 // See the documentation for Marshal for details about the conversion of Go
632 // values to YAML.
633 func (e *Encoder) Encode(v any) error {
634 return e.dumper.Dump(v)
635 }
636
637 // SetIndent changes the used indentation used when encoding.
638 func (e *Encoder) SetIndent(spaces int) {
639 e.dumper.SetIndent(spaces)
640 }
641
642 // CompactSeqIndent makes it so that '- ' is considered part of the indentation.
643 func (e *Encoder) CompactSeqIndent() {
644 e.dumper.SetCompactSeqIndent(true)
645 }
646
647 // DefaultSeqIndent makes it so that '- ' is not considered part of the indentation.
648 func (e *Encoder) DefaultSeqIndent() {
649 e.dumper.SetCompactSeqIndent(false)
650 }
651
652 // Close closes the encoder by writing any remaining data.
653 // It does not write a stream terminating string "...".
654 func (e *Encoder) Close() error {
655 return e.dumper.Close()
656 }
657
658 // Unmarshal decodes the first document found within the in byte slice
659 // and assigns decoded values into the out value.
660 //
661 // Maps and pointers (to a struct, string, int, etc) are accepted as out
662 // values. If an internal pointer within a struct is not initialized,
663 // the yaml package will initialize it if necessary for unmarshalling
664 // the provided data. The out parameter must not be nil.
665 //
666 // The type of the decoded values should be compatible with the respective
667 // values in out. If one or more values cannot be decoded due to a type
668 // mismatches, decoding continues partially until the end of the YAML
669 // content, and a *yaml.LoadErrors is returned with details for all
670 // missed values.
671 //
672 // Struct fields are only unmarshalled if they are exported (have an
673 // upper case first letter), and are unmarshalled using the field name
674 // lowercased as the default key. Custom keys may be defined via the
675 // "yaml" name in the field tag: the content preceding the first comma
676 // is used as the key, and the following comma-separated options are
677 // used to tweak the marshaling process (see Marshal).
678 // Conflicting names result in a runtime error.
679 //
680 // For example:
681 //
682 // type T struct {
683 // F int `yaml:"a,omitempty"`
684 // B int
685 // }
686 // var t T
687 // yaml.Construct([]byte("a: 1\nb: 2"), &t)
688 //
689 // See the documentation of Marshal for the format of tags and a list of
690 // supported tag options.
691 func Unmarshal(in []byte, out any) (err error) {
692 return Load(in, out, WithV3Defaults(), withFromLegacy())
693 }
694
695 // withFromLegacy is a private option that indicates this call is from
696 // a legacy API (Unmarshal/Decoder). It enables Unmarshaler interface
697 // checking and allows trailing content for backward compatibility.
698 func withFromLegacy() Option {
699 return func(o *libyaml.Options) error {
700 o.FromLegacy = true
701 return nil
702 }
703 }
704
705 // Marshal serializes the value provided into a YAML document. The structure
706 // of the generated document will reflect the structure of the value itself.
707 // Maps and pointers (to struct, string, int, etc) are accepted as the in value.
708 //
709 // Struct fields are only marshaled if they are exported (have an upper case
710 // first letter), and are marshaled using the field name lowercased as the
711 // default key. Custom keys may be defined via the "yaml" name in the field
712 // tag: the content preceding the first comma is used as the key, and the
713 // following comma-separated options are used to tweak the marshaling process.
714 // Conflicting names result in a runtime error.
715 //
716 // The field tag format accepted is:
717 //
718 // `(...) yaml:"[<key>][,<flag1>[,<flag2>]]" (...)`
719 //
720 // The following flags are currently supported:
721 //
722 // omitempty Only include the field if it's not set to the zero
723 // value for the type or to empty slices or maps.
724 // Zero valued structs will be omitted if all their public
725 // fields are zero, unless they implement an IsZero
726 // method (see the IsZeroer interface type), in which
727 // case the field will be excluded if IsZero returns true.
728 //
729 // flow Marshal using a flow style (useful for structs,
730 // sequences and maps).
731 //
732 // inline Inline the field, which must be a struct or a map,
733 // causing all of its fields or keys to be processed as if
734 // they were part of the outer struct. For maps, keys must
735 // not conflict with the yaml keys of other struct fields.
736 // See doc/inline-tags.md for detailed examples and use cases.
737 //
738 // In addition, if the key is "-", the field is ignored.
739 //
740 // For example:
741 //
742 // type T struct {
743 // F int `yaml:"a,omitempty"`
744 // B int
745 // }
746 // yaml.Marshal(&T{B: 2}) // Returns "b: 2\n"
747 // yaml.Marshal(&T{F: 1}} // Returns "a: 1\nb: 0\n"
748 func Marshal(in any) (out []byte, err error) {
749 // Use WithV3Defaults() with unlimited line width to match legacy DefaultOptions
750 return Dump(in, WithV3Defaults(), WithLineWidth(-1))
751 }