yaml.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. // Package yaml implements YAML support for the Go language.
  2. //
  3. // Source code and other details for the project are available at GitHub:
  4. //
  5. // https://github.com/go-yaml/yaml
  6. //
  7. package yaml
  8. import (
  9. "errors"
  10. "fmt"
  11. "reflect"
  12. "strings"
  13. "sync"
  14. )
  15. // MapSlice encodes and decodes as a YAML map.
  16. // The order of keys is preserved when encoding and decoding.
  17. type MapSlice []MapItem
  18. // MapItem is an item in a MapSlice.
  19. type MapItem struct {
  20. Key, Value interface{}
  21. }
  22. // The Unmarshaler interface may be implemented by types to customize their
  23. // behavior when being unmarshaled from a YAML document. The UnmarshalYAML
  24. // method receives a function that may be called to unmarshal the original
  25. // YAML value into a field or variable. It is safe to call the unmarshal
  26. // function parameter more than once if necessary.
  27. type Unmarshaler interface {
  28. UnmarshalYAML(unmarshal func(interface{}) error) error
  29. }
  30. // The Marshaler interface may be implemented by types to customize their
  31. // behavior when being marshaled into a YAML document. The returned value
  32. // is marshaled in place of the original value implementing Marshaler.
  33. //
  34. // If an error is returned by MarshalYAML, the marshaling procedure stops
  35. // and returns with the provided error.
  36. type Marshaler interface {
  37. MarshalYAML() (interface{}, error)
  38. }
  39. // Unmarshal decodes the first document found within the in byte slice
  40. // and assigns decoded values into the out value.
  41. //
  42. // Maps and pointers (to a struct, string, int, etc) are accepted as out
  43. // values. If an internal pointer within a struct is not initialized,
  44. // the yaml package will initialize it if necessary for unmarshalling
  45. // the provided data. The out parameter must not be nil.
  46. //
  47. // The type of the decoded values should be compatible with the respective
  48. // values in out. If one or more values cannot be decoded due to a type
  49. // mismatches, decoding continues partially until the end of the YAML
  50. // content, and a *yaml.TypeError is returned with details for all
  51. // missed values.
  52. //
  53. // Struct fields are only unmarshalled if they are exported (have an
  54. // upper case first letter), and are unmarshalled using the field name
  55. // lowercased as the default key. Custom keys may be defined via the
  56. // "yaml" name in the field tag: the content preceding the first comma
  57. // is used as the key, and the following comma-separated options are
  58. // used to tweak the marshalling process (see Marshal).
  59. // Conflicting names result in a runtime error.
  60. //
  61. // For example:
  62. //
  63. // type T struct {
  64. // F int `yaml:"a,omitempty"`
  65. // B int
  66. // }
  67. // var t T
  68. // yaml.Unmarshal([]byte("a: 1\nb: 2"), &t)
  69. //
  70. // See the documentation of Marshal for the format of tags and a list of
  71. // supported tag options.
  72. //
  73. func Unmarshal(in []byte, out interface{}) (err error) {
  74. return unmarshal(in, out, false)
  75. }
  76. // UnmarshalStrict is like Unmarshal except that any fields that are found
  77. // in the data that do not have corresponding struct members will result in
  78. // an error.
  79. func UnmarshalStrict(in []byte, out interface{}) (err error) {
  80. return unmarshal(in, out, true)
  81. }
  82. func unmarshal(in []byte, out interface{}, strict bool) (err error) {
  83. defer handleErr(&err)
  84. d := newDecoder(strict)
  85. p := newParser(in)
  86. defer p.destroy()
  87. node := p.parse()
  88. if node != nil {
  89. v := reflect.ValueOf(out)
  90. if v.Kind() == reflect.Ptr && !v.IsNil() {
  91. v = v.Elem()
  92. }
  93. d.unmarshal(node, v)
  94. }
  95. if len(d.terrors) > 0 {
  96. return &TypeError{d.terrors}
  97. }
  98. return nil
  99. }
  100. // Marshal serializes the value provided into a YAML document. The structure
  101. // of the generated document will reflect the structure of the value itself.
  102. // Maps and pointers (to struct, string, int, etc) are accepted as the in value.
  103. //
  104. // Struct fields are only unmarshalled if they are exported (have an upper case
  105. // first letter), and are unmarshalled using the field name lowercased as the
  106. // default key. Custom keys may be defined via the "yaml" name in the field
  107. // tag: the content preceding the first comma is used as the key, and the
  108. // following comma-separated options are used to tweak the marshalling process.
  109. // Conflicting names result in a runtime error.
  110. //
  111. // The field tag format accepted is:
  112. //
  113. // `(...) yaml:"[<key>][,<flag1>[,<flag2>]]" (...)`
  114. //
  115. // The following flags are currently supported:
  116. //
  117. // omitempty Only include the field if it's not set to the zero
  118. // value for the type or to empty slices or maps.
  119. // Does not apply to zero valued structs.
  120. //
  121. // flow Marshal using a flow style (useful for structs,
  122. // sequences and maps).
  123. //
  124. // inline Inline the field, which must be a struct or a map,
  125. // causing all of its fields or keys to be processed as if
  126. // they were part of the outer struct. For maps, keys must
  127. // not conflict with the yaml keys of other struct fields.
  128. //
  129. // In addition, if the key is "-", the field is ignored.
  130. //
  131. // For example:
  132. //
  133. // type T struct {
  134. // F int "a,omitempty"
  135. // B int
  136. // }
  137. // yaml.Marshal(&T{B: 2}) // Returns "b: 2\n"
  138. // yaml.Marshal(&T{F: 1}} // Returns "a: 1\nb: 0\n"
  139. //
  140. func Marshal(in interface{}) (out []byte, err error) {
  141. defer handleErr(&err)
  142. e := newEncoder()
  143. defer e.destroy()
  144. e.marshal("", reflect.ValueOf(in))
  145. e.finish()
  146. out = e.out
  147. return
  148. }
  149. func handleErr(err *error) {
  150. if v := recover(); v != nil {
  151. if e, ok := v.(yamlError); ok {
  152. *err = e.err
  153. } else {
  154. panic(v)
  155. }
  156. }
  157. }
  158. type yamlError struct {
  159. err error
  160. }
  161. func fail(err error) {
  162. panic(yamlError{err})
  163. }
  164. func failf(format string, args ...interface{}) {
  165. panic(yamlError{fmt.Errorf("yaml: "+format, args...)})
  166. }
  167. // A TypeError is returned by Unmarshal when one or more fields in
  168. // the YAML document cannot be properly decoded into the requested
  169. // types. When this error is returned, the value is still
  170. // unmarshaled partially.
  171. type TypeError struct {
  172. Errors []string
  173. }
  174. func (e *TypeError) Error() string {
  175. return fmt.Sprintf("yaml: unmarshal errors:\n %s", strings.Join(e.Errors, "\n "))
  176. }
  177. // --------------------------------------------------------------------------
  178. // Maintain a mapping of keys to structure field indexes
  179. // The code in this section was copied from mgo/bson.
  180. // structInfo holds details for the serialization of fields of
  181. // a given struct.
  182. type structInfo struct {
  183. FieldsMap map[string]fieldInfo
  184. FieldsList []fieldInfo
  185. // InlineMap is the number of the field in the struct that
  186. // contains an ,inline map, or -1 if there's none.
  187. InlineMap int
  188. }
  189. type fieldInfo struct {
  190. Key string
  191. Num int
  192. OmitEmpty bool
  193. Flow bool
  194. // Inline holds the field index if the field is part of an inlined struct.
  195. Inline []int
  196. }
  197. var structMap = make(map[reflect.Type]*structInfo)
  198. var fieldMapMutex sync.RWMutex
  199. func getStructInfo(st reflect.Type) (*structInfo, error) {
  200. fieldMapMutex.RLock()
  201. sinfo, found := structMap[st]
  202. fieldMapMutex.RUnlock()
  203. if found {
  204. return sinfo, nil
  205. }
  206. n := st.NumField()
  207. fieldsMap := make(map[string]fieldInfo)
  208. fieldsList := make([]fieldInfo, 0, n)
  209. inlineMap := -1
  210. for i := 0; i != n; i++ {
  211. field := st.Field(i)
  212. if field.PkgPath != "" && !field.Anonymous {
  213. continue // Private field
  214. }
  215. info := fieldInfo{Num: i}
  216. tag := field.Tag.Get("yaml")
  217. if tag == "" && strings.Index(string(field.Tag), ":") < 0 {
  218. tag = string(field.Tag)
  219. }
  220. if tag == "-" {
  221. continue
  222. }
  223. inline := false
  224. fields := strings.Split(tag, ",")
  225. if len(fields) > 1 {
  226. for _, flag := range fields[1:] {
  227. switch flag {
  228. case "omitempty":
  229. info.OmitEmpty = true
  230. case "flow":
  231. info.Flow = true
  232. case "inline":
  233. inline = true
  234. default:
  235. return nil, errors.New(fmt.Sprintf("Unsupported flag %q in tag %q of type %s", flag, tag, st))
  236. }
  237. }
  238. tag = fields[0]
  239. }
  240. if inline {
  241. switch field.Type.Kind() {
  242. case reflect.Map:
  243. if inlineMap >= 0 {
  244. return nil, errors.New("Multiple ,inline maps in struct " + st.String())
  245. }
  246. if field.Type.Key() != reflect.TypeOf("") {
  247. return nil, errors.New("Option ,inline needs a map with string keys in struct " + st.String())
  248. }
  249. inlineMap = info.Num
  250. case reflect.Struct:
  251. sinfo, err := getStructInfo(field.Type)
  252. if err != nil {
  253. return nil, err
  254. }
  255. for _, finfo := range sinfo.FieldsList {
  256. if _, found := fieldsMap[finfo.Key]; found {
  257. msg := "Duplicated key '" + finfo.Key + "' in struct " + st.String()
  258. return nil, errors.New(msg)
  259. }
  260. if finfo.Inline == nil {
  261. finfo.Inline = []int{i, finfo.Num}
  262. } else {
  263. finfo.Inline = append([]int{i}, finfo.Inline...)
  264. }
  265. fieldsMap[finfo.Key] = finfo
  266. fieldsList = append(fieldsList, finfo)
  267. }
  268. default:
  269. //return nil, errors.New("Option ,inline needs a struct value or map field")
  270. return nil, errors.New("Option ,inline needs a struct value field")
  271. }
  272. continue
  273. }
  274. if tag != "" {
  275. info.Key = tag
  276. } else {
  277. info.Key = strings.ToLower(field.Name)
  278. }
  279. if _, found = fieldsMap[info.Key]; found {
  280. msg := "Duplicated key '" + info.Key + "' in struct " + st.String()
  281. return nil, errors.New(msg)
  282. }
  283. fieldsList = append(fieldsList, info)
  284. fieldsMap[info.Key] = info
  285. }
  286. sinfo = &structInfo{fieldsMap, fieldsList, inlineMap}
  287. fieldMapMutex.Lock()
  288. structMap[st] = sinfo
  289. fieldMapMutex.Unlock()
  290. return sinfo, nil
  291. }
  292. func isZero(v reflect.Value) bool {
  293. switch v.Kind() {
  294. case reflect.String:
  295. return len(v.String()) == 0
  296. case reflect.Interface, reflect.Ptr:
  297. return v.IsNil()
  298. case reflect.Slice:
  299. return v.Len() == 0
  300. case reflect.Map:
  301. return v.Len() == 0
  302. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  303. return v.Int() == 0
  304. case reflect.Float32, reflect.Float64:
  305. return v.Float() == 0
  306. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  307. return v.Uint() == 0
  308. case reflect.Bool:
  309. return !v.Bool()
  310. case reflect.Struct:
  311. vt := v.Type()
  312. for i := v.NumField() - 1; i >= 0; i-- {
  313. if vt.Field(i).PkgPath != "" {
  314. continue // Private field
  315. }
  316. if !isZero(v.Field(i)) {
  317. return false
  318. }
  319. }
  320. return true
  321. }
  322. return false
  323. }