1 // Package yaml implements YAML support for the Go language.
3 // Source code and other details for the project are available at GitHub:
5 // https://github.com/go-yaml/yaml
18 // MapSlice encodes and decodes as a YAML map.
19 // The order of keys is preserved when encoding and decoding.
20 type MapSlice []MapItem
22 // MapItem is an item in a MapSlice.
24 Key, Value interface{}
27 // The Unmarshaler interface may be implemented by types to customize their
28 // behavior when being unmarshaled from a YAML document. The UnmarshalYAML
29 // method receives a function that may be called to unmarshal the original
30 // YAML value into a field or variable. It is safe to call the unmarshal
31 // function parameter more than once if necessary.
32 type Unmarshaler interface {
33 UnmarshalYAML(unmarshal func(interface{}) error) error
36 // The Marshaler interface may be implemented by types to customize their
37 // behavior when being marshaled into a YAML document. The returned value
38 // is marshaled in place of the original value implementing Marshaler.
40 // If an error is returned by MarshalYAML, the marshaling procedure stops
41 // and returns with the provided error.
42 type Marshaler interface {
43 MarshalYAML() (interface{}, error)
46 // Unmarshal decodes the first document found within the in byte slice
47 // and assigns decoded values into the out value.
49 // Maps and pointers (to a struct, string, int, etc) are accepted as out
50 // values. If an internal pointer within a struct is not initialized,
51 // the yaml package will initialize it if necessary for unmarshalling
52 // the provided data. The out parameter must not be nil.
54 // The type of the decoded values should be compatible with the respective
55 // values in out. If one or more values cannot be decoded due to a type
56 // mismatches, decoding continues partially until the end of the YAML
57 // content, and a *yaml.TypeError is returned with details for all
60 // Struct fields are only unmarshalled if they are exported (have an
61 // upper case first letter), and are unmarshalled using the field name
62 // lowercased as the default key. Custom keys may be defined via the
63 // "yaml" name in the field tag: the content preceding the first comma
64 // is used as the key, and the following comma-separated options are
65 // used to tweak the marshalling process (see Marshal).
66 // Conflicting names result in a runtime error.
71 // F int `yaml:"a,omitempty"`
75 // yaml.Unmarshal([]byte("a: 1\nb: 2"), &t)
77 // See the documentation of Marshal for the format of tags and a list of
78 // supported tag options.
80 func Unmarshal(in []byte, out interface{}) (err error) {
81 return unmarshal(in, out, false)
84 // UnmarshalStrict is like Unmarshal except that any fields that are found
85 // in the data that do not have corresponding struct members, or mapping
86 // keys that are duplicates, will result in
88 func UnmarshalStrict(in []byte, out interface{}) (err error) {
89 return unmarshal(in, out, true)
92 // A Decorder reads and decodes YAML values from an input stream.
98 // NewDecoder returns a new decoder that reads from r.
100 // The decoder introduces its own buffering and may read
101 // data from r beyond the YAML values requested.
102 func NewDecoder(r io.Reader) *Decoder {
104 parser: newParserFromReader(r),
108 // SetStrict sets whether strict decoding behaviour is enabled when
109 // decoding items in the data (see UnmarshalStrict). By default, decoding is not strict.
110 func (dec *Decoder) SetStrict(strict bool) {
114 // Decode reads the next YAML-encoded value from its input
115 // and stores it in the value pointed to by v.
117 // See the documentation for Unmarshal for details about the
118 // conversion of YAML into a Go value.
119 func (dec *Decoder) Decode(v interface{}) (err error) {
120 d := newDecoder(dec.strict)
121 defer handleErr(&err)
122 node := dec.parser.parse()
126 out := reflect.ValueOf(v)
127 if out.Kind() == reflect.Ptr && !out.IsNil() {
130 d.unmarshal(node, out)
131 if len(d.terrors) > 0 {
132 return &TypeError{d.terrors}
137 func unmarshal(in []byte, out interface{}, strict bool) (err error) {
138 defer handleErr(&err)
139 d := newDecoder(strict)
144 v := reflect.ValueOf(out)
145 if v.Kind() == reflect.Ptr && !v.IsNil() {
150 if len(d.terrors) > 0 {
151 return &TypeError{d.terrors}
156 // Marshal serializes the value provided into a YAML document. The structure
157 // of the generated document will reflect the structure of the value itself.
158 // Maps and pointers (to struct, string, int, etc) are accepted as the in value.
160 // Struct fields are only marshalled if they are exported (have an upper case
161 // first letter), and are marshalled using the field name lowercased as the
162 // default key. Custom keys may be defined via the "yaml" name in the field
163 // tag: the content preceding the first comma is used as the key, and the
164 // following comma-separated options are used to tweak the marshalling process.
165 // Conflicting names result in a runtime error.
167 // The field tag format accepted is:
169 // `(...) yaml:"[<key>][,<flag1>[,<flag2>]]" (...)`
171 // The following flags are currently supported:
173 // omitempty Only include the field if it's not set to the zero
174 // value for the type or to empty slices or maps.
175 // Zero valued structs will be omitted if all their public
176 // fields are zero, unless they implement an IsZero
177 // method (see the IsZeroer interface type), in which
178 // case the field will be included if that method returns true.
180 // flow Marshal using a flow style (useful for structs,
181 // sequences and maps).
183 // inline Inline the field, which must be a struct or a map,
184 // causing all of its fields or keys to be processed as if
185 // they were part of the outer struct. For maps, keys must
186 // not conflict with the yaml keys of other struct fields.
188 // In addition, if the key is "-", the field is ignored.
193 // F int `yaml:"a,omitempty"`
196 // yaml.Marshal(&T{B: 2}) // Returns "b: 2\n"
197 // yaml.Marshal(&T{F: 1}} // Returns "a: 1\nb: 0\n"
199 func Marshal(in interface{}) (out []byte, err error) {
200 defer handleErr(&err)
203 e.marshalDoc("", reflect.ValueOf(in))
209 // An Encoder writes YAML values to an output stream.
210 type Encoder struct {
214 // NewEncoder returns a new encoder that writes to w.
215 // The Encoder should be closed after use to flush all data
217 func NewEncoder(w io.Writer) *Encoder {
219 encoder: newEncoderWithWriter(w),
223 // Encode writes the YAML encoding of v to the stream.
224 // If multiple items are encoded to the stream, the
225 // second and subsequent document will be preceded
226 // with a "---" document separator, but the first will not.
228 // See the documentation for Marshal for details about the conversion of Go
230 func (e *Encoder) Encode(v interface{}) (err error) {
231 defer handleErr(&err)
232 e.encoder.marshalDoc("", reflect.ValueOf(v))
236 // Close closes the encoder by writing any remaining data.
237 // It does not write a stream terminating string "...".
238 func (e *Encoder) Close() (err error) {
239 defer handleErr(&err)
244 func handleErr(err *error) {
245 if v := recover(); v != nil {
246 if e, ok := v.(yamlError); ok {
254 type yamlError struct {
258 func fail(err error) {
259 panic(yamlError{err})
262 func failf(format string, args ...interface{}) {
263 panic(yamlError{fmt.Errorf("yaml: "+format, args...)})
266 // A TypeError is returned by Unmarshal when one or more fields in
267 // the YAML document cannot be properly decoded into the requested
268 // types. When this error is returned, the value is still
269 // unmarshaled partially.
270 type TypeError struct {
274 func (e *TypeError) Error() string {
275 return fmt.Sprintf("yaml: unmarshal errors:\n %s", strings.Join(e.Errors, "\n "))
278 // --------------------------------------------------------------------------
279 // Maintain a mapping of keys to structure field indexes
281 // The code in this section was copied from mgo/bson.
283 // structInfo holds details for the serialization of fields of
285 type structInfo struct {
286 FieldsMap map[string]fieldInfo
287 FieldsList []fieldInfo
289 // InlineMap is the number of the field in the struct that
290 // contains an ,inline map, or -1 if there's none.
294 type fieldInfo struct {
299 // Id holds the unique field identifier, so we can cheaply
300 // check for field duplicates without maintaining an extra map.
303 // Inline holds the field index if the field is part of an inlined struct.
307 var structMap = make(map[reflect.Type]*structInfo)
308 var fieldMapMutex sync.RWMutex
310 func getStructInfo(st reflect.Type) (*structInfo, error) {
311 fieldMapMutex.RLock()
312 sinfo, found := structMap[st]
313 fieldMapMutex.RUnlock()
319 fieldsMap := make(map[string]fieldInfo)
320 fieldsList := make([]fieldInfo, 0, n)
322 for i := 0; i != n; i++ {
324 if field.PkgPath != "" && !field.Anonymous {
325 continue // Private field
328 info := fieldInfo{Num: i}
330 tag := field.Tag.Get("yaml")
331 if tag == "" && strings.Index(string(field.Tag), ":") < 0 {
332 tag = string(field.Tag)
339 fields := strings.Split(tag, ",")
341 for _, flag := range fields[1:] {
344 info.OmitEmpty = true
350 return nil, errors.New(fmt.Sprintf("Unsupported flag %q in tag %q of type %s", flag, tag, st))
357 switch field.Type.Kind() {
360 return nil, errors.New("Multiple ,inline maps in struct " + st.String())
362 if field.Type.Key() != reflect.TypeOf("") {
363 return nil, errors.New("Option ,inline needs a map with string keys in struct " + st.String())
367 sinfo, err := getStructInfo(field.Type)
371 for _, finfo := range sinfo.FieldsList {
372 if _, found := fieldsMap[finfo.Key]; found {
373 msg := "Duplicated key '" + finfo.Key + "' in struct " + st.String()
374 return nil, errors.New(msg)
376 if finfo.Inline == nil {
377 finfo.Inline = []int{i, finfo.Num}
379 finfo.Inline = append([]int{i}, finfo.Inline...)
381 finfo.Id = len(fieldsList)
382 fieldsMap[finfo.Key] = finfo
383 fieldsList = append(fieldsList, finfo)
386 //return nil, errors.New("Option ,inline needs a struct value or map field")
387 return nil, errors.New("Option ,inline needs a struct value field")
395 info.Key = strings.ToLower(field.Name)
398 if _, found = fieldsMap[info.Key]; found {
399 msg := "Duplicated key '" + info.Key + "' in struct " + st.String()
400 return nil, errors.New(msg)
403 info.Id = len(fieldsList)
404 fieldsList = append(fieldsList, info)
405 fieldsMap[info.Key] = info
409 FieldsMap: fieldsMap,
410 FieldsList: fieldsList,
411 InlineMap: inlineMap,
415 structMap[st] = sinfo
416 fieldMapMutex.Unlock()
420 // IsZeroer is used to check whether an object is zero to
421 // determine whether it should be omitted when marshaling
422 // with the omitempty flag. One notable implementation
424 type IsZeroer interface {
428 func isZero(v reflect.Value) bool {
430 if z, ok := v.Interface().(IsZeroer); ok {
431 if (kind == reflect.Ptr || kind == reflect.Interface) && v.IsNil() {
438 return len(v.String()) == 0
439 case reflect.Interface, reflect.Ptr:
445 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
447 case reflect.Float32, reflect.Float64:
448 return v.Float() == 0
449 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
455 for i := v.NumField() - 1; i >= 0; i-- {
456 if vt.Field(i).PkgPath != "" {
457 continue // Private field
459 if !isZero(v.Field(i)) {