You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

346 lines
9.6 KiB

  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. defer handleErr(&err)
  75. d := newDecoder()
  76. p := newParser(in)
  77. defer p.destroy()
  78. node := p.parse()
  79. if node != nil {
  80. v := reflect.ValueOf(out)
  81. if v.Kind() == reflect.Ptr && !v.IsNil() {
  82. v = v.Elem()
  83. }
  84. d.unmarshal(node, v)
  85. }
  86. if len(d.terrors) > 0 {
  87. return &TypeError{d.terrors}
  88. }
  89. return nil
  90. }
  91. // Marshal serializes the value provided into a YAML document. The structure
  92. // of the generated document will reflect the structure of the value itself.
  93. // Maps and pointers (to struct, string, int, etc) are accepted as the in value.
  94. //
  95. // Struct fields are only unmarshalled if they are exported (have an upper case
  96. // first letter), and are unmarshalled using the field name lowercased as the
  97. // default key. Custom keys may be defined via the "yaml" name in the field
  98. // tag: the content preceding the first comma is used as the key, and the
  99. // following comma-separated options are used to tweak the marshalling process.
  100. // Conflicting names result in a runtime error.
  101. //
  102. // The field tag format accepted is:
  103. //
  104. // `(...) yaml:"[<key>][,<flag1>[,<flag2>]]" (...)`
  105. //
  106. // The following flags are currently supported:
  107. //
  108. // omitempty Only include the field if it's not set to the zero
  109. // value for the type or to empty slices or maps.
  110. // Does not apply to zero valued structs.
  111. //
  112. // flow Marshal using a flow style (useful for structs,
  113. // sequences and maps).
  114. //
  115. // inline Inline the field, which must be a struct or a map,
  116. // causing all of its fields or keys to be processed as if
  117. // they were part of the outer struct. For maps, keys must
  118. // not conflict with the yaml keys of other struct fields.
  119. //
  120. // In addition, if the key is "-", the field is ignored.
  121. //
  122. // For example:
  123. //
  124. // type T struct {
  125. // F int "a,omitempty"
  126. // B int
  127. // }
  128. // yaml.Marshal(&T{B: 2}) // Returns "b: 2\n"
  129. // yaml.Marshal(&T{F: 1}} // Returns "a: 1\nb: 0\n"
  130. //
  131. func Marshal(in interface{}) (out []byte, err error) {
  132. defer handleErr(&err)
  133. e := newEncoder()
  134. defer e.destroy()
  135. e.marshal("", reflect.ValueOf(in))
  136. e.finish()
  137. out = e.out
  138. return
  139. }
  140. func handleErr(err *error) {
  141. if v := recover(); v != nil {
  142. if e, ok := v.(yamlError); ok {
  143. *err = e.err
  144. } else {
  145. panic(v)
  146. }
  147. }
  148. }
  149. type yamlError struct {
  150. err error
  151. }
  152. func fail(err error) {
  153. panic(yamlError{err})
  154. }
  155. func failf(format string, args ...interface{}) {
  156. panic(yamlError{fmt.Errorf("yaml: "+format, args...)})
  157. }
  158. // A TypeError is returned by Unmarshal when one or more fields in
  159. // the YAML document cannot be properly decoded into the requested
  160. // types. When this error is returned, the value is still
  161. // unmarshaled partially.
  162. type TypeError struct {
  163. Errors []string
  164. }
  165. func (e *TypeError) Error() string {
  166. return fmt.Sprintf("yaml: unmarshal errors:\n %s", strings.Join(e.Errors, "\n "))
  167. }
  168. // --------------------------------------------------------------------------
  169. // Maintain a mapping of keys to structure field indexes
  170. // The code in this section was copied from mgo/bson.
  171. // structInfo holds details for the serialization of fields of
  172. // a given struct.
  173. type structInfo struct {
  174. FieldsMap map[string]fieldInfo
  175. FieldsList []fieldInfo
  176. // InlineMap is the number of the field in the struct that
  177. // contains an ,inline map, or -1 if there's none.
  178. InlineMap int
  179. }
  180. type fieldInfo struct {
  181. Key string
  182. Num int
  183. OmitEmpty bool
  184. Flow bool
  185. // Inline holds the field index if the field is part of an inlined struct.
  186. Inline []int
  187. }
  188. var structMap = make(map[reflect.Type]*structInfo)
  189. var fieldMapMutex sync.RWMutex
  190. func getStructInfo(st reflect.Type) (*structInfo, error) {
  191. fieldMapMutex.RLock()
  192. sinfo, found := structMap[st]
  193. fieldMapMutex.RUnlock()
  194. if found {
  195. return sinfo, nil
  196. }
  197. n := st.NumField()
  198. fieldsMap := make(map[string]fieldInfo)
  199. fieldsList := make([]fieldInfo, 0, n)
  200. inlineMap := -1
  201. for i := 0; i != n; i++ {
  202. field := st.Field(i)
  203. if field.PkgPath != "" && !field.Anonymous {
  204. continue // Private field
  205. }
  206. info := fieldInfo{Num: i}
  207. tag := field.Tag.Get("yaml")
  208. if tag == "" && strings.Index(string(field.Tag), ":") < 0 {
  209. tag = string(field.Tag)
  210. }
  211. if tag == "-" {
  212. continue
  213. }
  214. inline := false
  215. fields := strings.Split(tag, ",")
  216. if len(fields) > 1 {
  217. for _, flag := range fields[1:] {
  218. switch flag {
  219. case "omitempty":
  220. info.OmitEmpty = true
  221. case "flow":
  222. info.Flow = true
  223. case "inline":
  224. inline = true
  225. default:
  226. return nil, errors.New(fmt.Sprintf("Unsupported flag %q in tag %q of type %s", flag, tag, st))
  227. }
  228. }
  229. tag = fields[0]
  230. }
  231. if inline {
  232. switch field.Type.Kind() {
  233. case reflect.Map:
  234. if inlineMap >= 0 {
  235. return nil, errors.New("Multiple ,inline maps in struct " + st.String())
  236. }
  237. if field.Type.Key() != reflect.TypeOf("") {
  238. return nil, errors.New("Option ,inline needs a map with string keys in struct " + st.String())
  239. }
  240. inlineMap = info.Num
  241. case reflect.Struct:
  242. sinfo, err := getStructInfo(field.Type)
  243. if err != nil {
  244. return nil, err
  245. }
  246. for _, finfo := range sinfo.FieldsList {
  247. if _, found := fieldsMap[finfo.Key]; found {
  248. msg := "Duplicated key '" + finfo.Key + "' in struct " + st.String()
  249. return nil, errors.New(msg)
  250. }
  251. if finfo.Inline == nil {
  252. finfo.Inline = []int{i, finfo.Num}
  253. } else {
  254. finfo.Inline = append([]int{i}, finfo.Inline...)
  255. }
  256. fieldsMap[finfo.Key] = finfo
  257. fieldsList = append(fieldsList, finfo)
  258. }
  259. default:
  260. //return nil, errors.New("Option ,inline needs a struct value or map field")
  261. return nil, errors.New("Option ,inline needs a struct value field")
  262. }
  263. continue
  264. }
  265. if tag != "" {
  266. info.Key = tag
  267. } else {
  268. info.Key = strings.ToLower(field.Name)
  269. }
  270. if _, found = fieldsMap[info.Key]; found {
  271. msg := "Duplicated key '" + info.Key + "' in struct " + st.String()
  272. return nil, errors.New(msg)
  273. }
  274. fieldsList = append(fieldsList, info)
  275. fieldsMap[info.Key] = info
  276. }
  277. sinfo = &structInfo{fieldsMap, fieldsList, inlineMap}
  278. fieldMapMutex.Lock()
  279. structMap[st] = sinfo
  280. fieldMapMutex.Unlock()
  281. return sinfo, nil
  282. }
  283. func isZero(v reflect.Value) bool {
  284. switch v.Kind() {
  285. case reflect.String:
  286. return len(v.String()) == 0
  287. case reflect.Interface, reflect.Ptr:
  288. return v.IsNil()
  289. case reflect.Slice:
  290. return v.Len() == 0
  291. case reflect.Map:
  292. return v.Len() == 0
  293. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  294. return v.Int() == 0
  295. case reflect.Float32, reflect.Float64:
  296. return v.Float() == 0
  297. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  298. return v.Uint() == 0
  299. case reflect.Bool:
  300. return !v.Bool()
  301. case reflect.Struct:
  302. vt := v.Type()
  303. for i := v.NumField() - 1; i >= 0; i-- {
  304. if vt.Field(i).PkgPath != "" {
  305. continue // Private field
  306. }
  307. if !isZero(v.Field(i)) {
  308. return false
  309. }
  310. }
  311. return true
  312. }
  313. return false
  314. }