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
17 // MapSlice encodes and decodes as a YAML map.
18 // The order of keys is preserved when encoding and decoding.
19 type MapSlice []MapItem
21 // MapItem is an item in a MapSlice.
23 Key, Value interface{}
26 // The Unmarshaler interface may be implemented by types to customize their
27 // behavior when being unmarshaled from a YAML document. The UnmarshalYAML
28 // method receives a function that may be called to unmarshal the original
29 // YAML value into a field or variable. It is safe to call the unmarshal
30 // function parameter more than once if necessary.
31 type Unmarshaler interface {
32 UnmarshalYAML(unmarshal func(interface{}) error) error
35 // The Marshaler interface may be implemented by types to customize their
36 // behavior when being marshaled into a YAML document. The returned value
37 // is marshaled in place of the original value implementing Marshaler.
39 // If an error is returned by MarshalYAML, the marshaling procedure stops
40 // and returns with the provided error.
41 type Marshaler interface {
42 MarshalYAML() (interface{}, error)
45 // Unmarshal decodes the first document found within the in byte slice
46 // and assigns decoded values into the out value.
48 // Maps and pointers (to a struct, string, int, etc) are accepted as out
49 // values. If an internal pointer within a struct is not initialized,
50 // the yaml package will initialize it if necessary for unmarshalling
51 // the provided data. The out parameter must not be nil.
53 // The type of the decoded values should be compatible with the respective
54 // values in out. If one or more values cannot be decoded due to a type
55 // mismatches, decoding continues partially until the end of the YAML
56 // content, and a *yaml.TypeError is returned with details for all
59 // Struct fields are only unmarshalled if they are exported (have an
60 // upper case first letter), and are unmarshalled using the field name
61 // lowercased as the default key. Custom keys may be defined via the
62 // "yaml" name in the field tag: the content preceding the first comma
63 // is used as the key, and the following comma-separated options are
64 // used to tweak the marshalling process (see Marshal).
65 // Conflicting names result in a runtime error.
70 // F int `yaml:"a,omitempty"`
74 // yaml.Unmarshal([]byte("a: 1\nb: 2"), &t)
76 // See the documentation of Marshal for the format of tags and a list of
77 // supported tag options.
79 func Unmarshal(in []byte, out interface{}) (err error) {
80 return unmarshal(in, out, false)
83 // UnmarshalStrict is like Unmarshal except that any fields that are found
84 // in the data that do not have corresponding struct members will result in
86 func UnmarshalStrict(in []byte, out interface{}) (err error) {
87 return unmarshal(in, out, true)
90 func unmarshal(in []byte, out interface{}, strict bool) (err error) {
92 d := newDecoder(strict)
97 v := reflect.ValueOf(out)
98 if v.Kind() == reflect.Ptr && !v.IsNil() {
103 if len(d.terrors) > 0 {
104 return &TypeError{d.terrors}
109 // Marshal serializes the value provided into a YAML document. The structure
110 // of the generated document will reflect the structure of the value itself.
111 // Maps and pointers (to struct, string, int, etc) are accepted as the in value.
113 // Struct fields are only unmarshalled if they are exported (have an upper case
114 // first letter), and are unmarshalled using the field name lowercased as the
115 // default key. Custom keys may be defined via the "yaml" name in the field
116 // tag: the content preceding the first comma is used as the key, and the
117 // following comma-separated options are used to tweak the marshalling process.
118 // Conflicting names result in a runtime error.
120 // The field tag format accepted is:
122 // `(...) yaml:"[<key>][,<flag1>[,<flag2>]]" (...)`
124 // The following flags are currently supported:
126 // omitempty Only include the field if it's not set to the zero
127 // value for the type or to empty slices or maps.
128 // Does not apply to zero valued structs.
130 // flow Marshal using a flow style (useful for structs,
131 // sequences and maps).
133 // inline Inline the field, which must be a struct or a map,
134 // causing all of its fields or keys to be processed as if
135 // they were part of the outer struct. For maps, keys must
136 // not conflict with the yaml keys of other struct fields.
138 // In addition, if the key is "-", the field is ignored.
143 // F int "a,omitempty"
146 // yaml.Marshal(&T{B: 2}) // Returns "b: 2\n"
147 // yaml.Marshal(&T{F: 1}} // Returns "a: 1\nb: 0\n"
149 func Marshal(in interface{}) (out []byte, err error) {
150 defer handleErr(&err)
153 e.marshal("", reflect.ValueOf(in))
159 func handleErr(err *error) {
160 if v := recover(); v != nil {
161 if e, ok := v.(yamlError); ok {
169 type yamlError struct {
173 func fail(err error) {
174 panic(yamlError{err})
177 func failf(format string, args ...interface{}) {
178 panic(yamlError{fmt.Errorf("yaml: "+format, args...)})
181 // A TypeError is returned by Unmarshal when one or more fields in
182 // the YAML document cannot be properly decoded into the requested
183 // types. When this error is returned, the value is still
184 // unmarshaled partially.
185 type TypeError struct {
189 func (e *TypeError) Error() string {
190 return fmt.Sprintf("yaml: unmarshal errors:\n %s", strings.Join(e.Errors, "\n "))
193 // --------------------------------------------------------------------------
194 // Maintain a mapping of keys to structure field indexes
196 // The code in this section was copied from mgo/bson.
198 // structInfo holds details for the serialization of fields of
200 type structInfo struct {
201 FieldsMap map[string]fieldInfo
202 FieldsList []fieldInfo
204 // InlineMap is the number of the field in the struct that
205 // contains an ,inline map, or -1 if there's none.
209 type fieldInfo struct {
215 // Inline holds the field index if the field is part of an inlined struct.
219 var structMap = make(map[reflect.Type]*structInfo)
220 var fieldMapMutex sync.RWMutex
222 func getStructInfo(st reflect.Type) (*structInfo, error) {
223 fieldMapMutex.RLock()
224 sinfo, found := structMap[st]
225 fieldMapMutex.RUnlock()
231 fieldsMap := make(map[string]fieldInfo)
232 fieldsList := make([]fieldInfo, 0, n)
234 for i := 0; i != n; i++ {
236 if field.PkgPath != "" && !field.Anonymous {
237 continue // Private field
240 info := fieldInfo{Num: i}
242 tag := field.Tag.Get("yaml")
243 if tag == "" && strings.Index(string(field.Tag), ":") < 0 {
244 tag = string(field.Tag)
251 fields := strings.Split(tag, ",")
253 for _, flag := range fields[1:] {
256 info.OmitEmpty = true
262 return nil, errors.New(fmt.Sprintf("Unsupported flag %q in tag %q of type %s", flag, tag, st))
269 switch field.Type.Kind() {
272 return nil, errors.New("Multiple ,inline maps in struct " + st.String())
274 if field.Type.Key() != reflect.TypeOf("") {
275 return nil, errors.New("Option ,inline needs a map with string keys in struct " + st.String())
279 sinfo, err := getStructInfo(field.Type)
283 for _, finfo := range sinfo.FieldsList {
284 if _, found := fieldsMap[finfo.Key]; found {
285 msg := "Duplicated key '" + finfo.Key + "' in struct " + st.String()
286 return nil, errors.New(msg)
288 if finfo.Inline == nil {
289 finfo.Inline = []int{i, finfo.Num}
291 finfo.Inline = append([]int{i}, finfo.Inline...)
293 fieldsMap[finfo.Key] = finfo
294 fieldsList = append(fieldsList, finfo)
297 //return nil, errors.New("Option ,inline needs a struct value or map field")
298 return nil, errors.New("Option ,inline needs a struct value field")
306 info.Key = strings.ToLower(field.Name)
309 if _, found = fieldsMap[info.Key]; found {
310 msg := "Duplicated key '" + info.Key + "' in struct " + st.String()
311 return nil, errors.New(msg)
314 fieldsList = append(fieldsList, info)
315 fieldsMap[info.Key] = info
318 sinfo = &structInfo{fieldsMap, fieldsList, inlineMap}
321 structMap[st] = sinfo
322 fieldMapMutex.Unlock()
326 func isZero(v reflect.Value) bool {
329 return len(v.String()) == 0
330 case reflect.Interface, reflect.Ptr:
336 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
338 case reflect.Float32, reflect.Float64:
339 return v.Float() == 0
340 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
346 for i := v.NumField() - 1; i >= 0; i-- {
347 if vt.Field(i).PkgPath != "" {
348 continue // Private field
350 if !isZero(v.Field(i)) {