yaml.go 11 KB

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