| 1 | // Copyright 2025 The go-yaml Project Contributors |
| 2 | // SPDX-License-Identifier: Apache-2.0 |
| 3 | |
| 4 | // This file contains the Loader API for reading YAML documents. |
| 5 | // |
| 6 | // Primary functions: |
| 7 | // - Load: Decode YAML document(s) into a value (use WithAll for multi-doc) |
| 8 | // - NewLoader: Create a streaming loader from io.Reader |
| 9 | |
| 10 | package libyaml |
| 11 | |
| 12 | import ( |
| 13 | "bytes" |
| 14 | "errors" |
| 15 | "io" |
| 16 | "reflect" |
| 17 | ) |
| 18 | |
| 19 | // A Loader reads and loads YAML values from an input stream with configurable |
| 20 | // options. |
| 21 | type Loader struct { |
| 22 | composer *Composer |
| 23 | resolver *Resolver |
| 24 | constructor *Constructor |
| 25 | options *Options |
| 26 | docCount int |
| 27 | } |
| 28 | |
| 29 | // NewLoader returns a new Loader that reads from r with the given options. |
| 30 | // |
| 31 | // The Loader introduces its own buffering and may read data from r beyond the |
| 32 | // YAML values requested. |
| 33 | func NewLoader(r io.Reader, opts ...Option) (*Loader, error) { |
| 34 | o, err := ApplyOptions(opts...) |
| 35 | if err != nil { |
| 36 | return nil, err |
| 37 | } |
| 38 | c := NewComposerFromReader(r, o) |
| 39 | c.SetStreamNodes(o.StreamNodes) |
| 40 | return &Loader{ |
| 41 | composer: c, |
| 42 | resolver: NewResolver(o), |
| 43 | constructor: NewConstructor(o), |
| 44 | options: o, |
| 45 | }, nil |
| 46 | } |
| 47 | |
| 48 | // Load loads YAML document(s) with the given options. |
| 49 | // |
| 50 | // By default, Load requires exactly one document in the input. |
| 51 | // If zero documents are found, it returns an error. |
| 52 | // If multiple documents are found, it returns an error. |
| 53 | // |
| 54 | // Use WithAllDocuments() to load all documents into a slice: |
| 55 | // |
| 56 | // var configs []Config |
| 57 | // yaml.Load(multiDocYAML, &configs, yaml.WithAllDocuments()) |
| 58 | // |
| 59 | // When WithAllDocuments is used, out must be a pointer to a slice. |
| 60 | // Each document is loaded into the slice element type. |
| 61 | // Zero documents results in an empty slice (no error). |
| 62 | // |
| 63 | // Maps and pointers (to a struct, string, int, etc) are accepted as out |
| 64 | // values. If an internal pointer within a struct is not initialized, |
| 65 | // the yaml package will initialize it if necessary. The out parameter |
| 66 | // must not be nil. |
| 67 | // |
| 68 | // The type of the loaded values should be compatible with the respective |
| 69 | // values in out. If one or more values cannot be loaded due to type |
| 70 | // mismatches, decoding continues partially until the end of the YAML |
| 71 | // content, and a *yaml.LoadErrors is returned with details for all |
| 72 | // missed values. |
| 73 | // |
| 74 | // Struct fields are only loaded if they are exported (have an upper case |
| 75 | // first letter), and are loaded using the field name lowercased as the |
| 76 | // default key. Custom keys may be defined via the "yaml" name in the field |
| 77 | // tag: the content preceding the first comma is used as the key, and the |
| 78 | // following comma-separated options control the loading and dumping behavior. |
| 79 | // |
| 80 | // For example: |
| 81 | // |
| 82 | // type T struct { |
| 83 | // F int `yaml:"a,omitempty"` |
| 84 | // B int |
| 85 | // } |
| 86 | // var t T |
| 87 | // yaml.Load([]byte("a: 1\nb: 2"), &t) |
| 88 | // |
| 89 | // See the documentation of Dump for the format of tags and a list of |
| 90 | // supported tag options. |
| 91 | func Load(in []byte, out any, opts ...Option) error { |
| 92 | o, err := ApplyOptions(opts...) |
| 93 | if err != nil { |
| 94 | return err |
| 95 | } |
| 96 | |
| 97 | if o.AllDocuments { |
| 98 | // Multi-document mode: out must be pointer to slice |
| 99 | return loadAll(in, out, o) |
| 100 | } |
| 101 | |
| 102 | // Single-document mode: exactly one document required |
| 103 | return loadSingle(in, out, o) |
| 104 | } |
| 105 | |
| 106 | // Load reads the next YAML-encoded document from its input and stores it |
| 107 | // in the value pointed to by v. |
| 108 | // |
| 109 | // Returns [io.EOF] when there are no more documents to read. |
| 110 | // If WithSingleDocument option was set and a document was already read, |
| 111 | // subsequent calls return [io.EOF]. |
| 112 | // |
| 113 | // Maps and pointers (to a struct, string, int, etc) are accepted as v |
| 114 | // values. If an internal pointer within a struct is not initialized, |
| 115 | // the yaml package will initialize it if necessary. The v parameter |
| 116 | // must not be nil. |
| 117 | // |
| 118 | // Struct fields are only loaded if they are exported (have an upper case |
| 119 | // first letter), and are loaded using the field name lowercased as the |
| 120 | // default key. Custom keys may be defined via the "yaml" name in the field |
| 121 | // tag: the content preceding the first comma is used as the key, and the |
| 122 | // following comma-separated options control the loading and dumping behavior. |
| 123 | // |
| 124 | // See the documentation of the package-level Load function for more details |
| 125 | // about YAML to Go conversion and tag options. |
| 126 | func (l *Loader) Load(v any) (err error) { |
| 127 | defer handleErr(&err) |
| 128 | if l.options.SingleDocument && l.docCount > 0 { |
| 129 | return io.EOF |
| 130 | } |
| 131 | |
| 132 | // Stage 1: Compose - parse events into node tree (unresolved tags) |
| 133 | node := l.composer.Compose() // *Node |
| 134 | if node == nil { |
| 135 | return io.EOF |
| 136 | } |
| 137 | l.docCount++ |
| 138 | |
| 139 | // Stage 2: Resolve - determine implicit types for untagged scalars |
| 140 | l.resolver.Resolve(node) |
| 141 | |
| 142 | // Stage 3: Construct - convert node tree to Go values |
| 143 | out := reflect.ValueOf(v) |
| 144 | if out.Kind() == reflect.Pointer && !out.IsNil() { |
| 145 | out = out.Elem() |
| 146 | } |
| 147 | l.constructor.Construct(node, out) |
| 148 | if len(l.constructor.TypeErrors) > 0 { |
| 149 | typeErrors := l.constructor.TypeErrors |
| 150 | l.constructor.TypeErrors = nil |
| 151 | return &LoadErrors{Errors: typeErrors} |
| 152 | } |
| 153 | return nil |
| 154 | } |
| 155 | |
| 156 | // loadAll loads all documents from the input into a slice. |
| 157 | // The out parameter must be a non-nil pointer to a slice. |
| 158 | // Each document is appended to the slice as an element. |
| 159 | func loadAll(in []byte, out any, opts *Options) error { |
| 160 | outVal := reflect.ValueOf(out) |
| 161 | if outVal.Kind() != reflect.Pointer || outVal.IsNil() { |
| 162 | msg := "yaml: WithAllDocuments requires a non-nil pointer to a slice" |
| 163 | return &LoadErrors{Errors: []*LoadError{{ |
| 164 | Stage: ConstructorStage, |
| 165 | Message: msg, |
| 166 | err: errors.New(msg), |
| 167 | }}} |
| 168 | } |
| 169 | |
| 170 | sliceVal := outVal.Elem() |
| 171 | if sliceVal.Kind() != reflect.Slice { |
| 172 | msg := "yaml: WithAllDocuments requires a pointer to a slice" |
| 173 | return &LoadErrors{Errors: []*LoadError{{ |
| 174 | Stage: ConstructorStage, |
| 175 | Message: msg, |
| 176 | err: errors.New(msg), |
| 177 | }}} |
| 178 | } |
| 179 | |
| 180 | // Create a new slice (clear existing content) |
| 181 | sliceVal.Set(reflect.MakeSlice(sliceVal.Type(), 0, 0)) |
| 182 | |
| 183 | l, err := NewLoader(bytes.NewReader(in), func(o *Options) error { |
| 184 | *o = *opts // Copy options |
| 185 | return nil |
| 186 | }) |
| 187 | if err != nil { |
| 188 | return err |
| 189 | } |
| 190 | |
| 191 | elemType := sliceVal.Type().Elem() |
| 192 | for { |
| 193 | // Create new element of slice's element type |
| 194 | elemPtr := reflect.New(elemType) |
| 195 | err := l.Load(elemPtr.Interface()) |
| 196 | if err == io.EOF { |
| 197 | break |
| 198 | } |
| 199 | if err != nil { |
| 200 | return err |
| 201 | } |
| 202 | // Append loaded element to slice |
| 203 | sliceVal.Set(reflect.Append(sliceVal, elemPtr.Elem())) |
| 204 | } |
| 205 | |
| 206 | return nil |
| 207 | } |
| 208 | |
| 209 | // loadSingle loads exactly one document from the input. |
| 210 | // Returns an error if the input contains zero or multiple documents |
| 211 | // (unless FromLegacy option is set for backward compatibility). |
| 212 | func loadSingle(in []byte, out any, opts *Options) error { |
| 213 | l, err := NewLoader(bytes.NewReader(in), func(o *Options) error { |
| 214 | *o = *opts // Copy options |
| 215 | return nil |
| 216 | }) |
| 217 | if err != nil { |
| 218 | return err |
| 219 | } |
| 220 | |
| 221 | // Load first document |
| 222 | err = l.Load(out) |
| 223 | if err == io.EOF { |
| 224 | if opts.FromLegacy { |
| 225 | return nil |
| 226 | } |
| 227 | msg := "yaml: no documents in stream" |
| 228 | return &LoadErrors{Errors: []*LoadError{{ |
| 229 | Stage: ConstructorStage, |
| 230 | Message: msg, |
| 231 | err: errors.New(msg), |
| 232 | }}} |
| 233 | } |
| 234 | if err != nil { |
| 235 | return err |
| 236 | } |
| 237 | |
| 238 | // Skip trailing document check for legacy Unmarshal() compatibility |
| 239 | if opts.FromLegacy { |
| 240 | return nil |
| 241 | } |
| 242 | |
| 243 | // Check for additional documents |
| 244 | var dummy any |
| 245 | err = l.Load(&dummy) |
| 246 | if err != io.EOF { |
| 247 | if err != nil { |
| 248 | // Some other error occurred |
| 249 | return err |
| 250 | } |
| 251 | // Successfully loaded a second document - this is an error in strict mode |
| 252 | msg := "yaml: expected single document, found multiple" |
| 253 | return &LoadErrors{Errors: []*LoadError{{ |
| 254 | Stage: ConstructorStage, |
| 255 | Message: msg, |
| 256 | err: errors.New(msg), |
| 257 | }}} |
| 258 | } |
| 259 | |
| 260 | return nil |
| 261 | } |
| 262 | |
| 263 | // SetKnownFields enables or disables strict field checking for subsequent Load |
| 264 | // calls. |
| 265 | // This is used by the legacy Decoder.KnownFields() method. |
| 266 | func (l *Loader) SetKnownFields(enable bool) { |
| 267 | l.constructor.KnownFields = enable |
| 268 | } |
| 269 | |
| 270 | // ComposeAndResolve composes and resolves the next document from the input |
| 271 | // and returns the node without constructing Go values. This is used by |
| 272 | // Unmarshal() to support the Unmarshaler interface. |
| 273 | func (l *Loader) ComposeAndResolve() *Node { |
| 274 | if l.options.SingleDocument && l.docCount > 0 { |
| 275 | return nil |
| 276 | } |
| 277 | |
| 278 | // Stage 1: Compose - parse events into node tree (unresolved tags) |
| 279 | node := l.composer.Compose() |
| 280 | if node == nil { |
| 281 | return nil |
| 282 | } |
| 283 | l.docCount++ |
| 284 | |
| 285 | // Stage 2: Resolve - determine implicit types for untagged scalars |
| 286 | l.resolver.Resolve(node) |
| 287 | |
| 288 | return node |
| 289 | } |
| 290 | |
| 291 | // LoadAny parses YAML data into generic Go structures (map[string]any, []any). |
| 292 | // |
| 293 | // Useful for test data loading where the structure is unknown at compile time. |
| 294 | // This is a convenience wrapper around Load with an any target. |
| 295 | func LoadAny(data []byte) (any, error) { |
| 296 | var result any |
| 297 | if err := Load(data, &result); err != nil { |
| 298 | return nil, err |
| 299 | } |
| 300 | return result, nil |
| 301 | } |