//1// Copyright (c) 2011-2019 Canonical Ltd2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.1415// Package yaml implements YAML support for the Go language.16//17// Source code and other details for the project are available at GitHub:18//19// https://github.com/go-yaml/yaml20//21package yaml2223import (24"errors"25"fmt"26"io"27"reflect"28"strings"29"sync"30"unicode/utf8"31)3233// The Unmarshaler interface may be implemented by types to customize their34// behavior when being unmarshaled from a YAML document.35type Unmarshaler interface {36UnmarshalYAML(value *Node) error37}3839type obsoleteUnmarshaler interface {40UnmarshalYAML(unmarshal func(interface{}) error) error41}4243// The Marshaler interface may be implemented by types to customize their44// behavior when being marshaled into a YAML document. The returned value45// is marshaled in place of the original value implementing Marshaler.46//47// If an error is returned by MarshalYAML, the marshaling procedure stops48// and returns with the provided error.49type Marshaler interface {50MarshalYAML() (interface{}, error)51}5253// Unmarshal decodes the first document found within the in byte slice54// and assigns decoded values into the out value.55//56// Maps and pointers (to a struct, string, int, etc) are accepted as out57// values. If an internal pointer within a struct is not initialized,58// the yaml package will initialize it if necessary for unmarshalling59// the provided data. The out parameter must not be nil.60//61// The type of the decoded values should be compatible with the respective62// values in out. If one or more values cannot be decoded due to a type63// mismatches, decoding continues partially until the end of the YAML64// content, and a *yaml.TypeError is returned with details for all65// missed values.66//67// Struct fields are only unmarshalled if they are exported (have an68// upper case first letter), and are unmarshalled using the field name69// lowercased as the default key. Custom keys may be defined via the70// "yaml" name in the field tag: the content preceding the first comma71// is used as the key, and the following comma-separated options are72// used to tweak the marshalling process (see Marshal).73// Conflicting names result in a runtime error.74//75// For example:76//77// type T struct {78// F int `yaml:"a,omitempty"`79// B int80// }81// var t T82// yaml.Unmarshal([]byte("a: 1\nb: 2"), &t)83//84// See the documentation of Marshal for the format of tags and a list of85// supported tag options.86//87func Unmarshal(in []byte, out interface{}) (err error) {88return unmarshal(in, out, false)89}9091// A Decoder reads and decodes YAML values from an input stream.92type Decoder struct {93parser *parser94knownFields bool95}9697// NewDecoder returns a new decoder that reads from r.98//99// The decoder introduces its own buffering and may read100// data from r beyond the YAML values requested.101func NewDecoder(r io.Reader) *Decoder {102return &Decoder{103parser: newParserFromReader(r),104}105}106107// KnownFields ensures that the keys in decoded mappings to108// exist as fields in the struct being decoded into.109func (dec *Decoder) KnownFields(enable bool) {110dec.knownFields = enable111}112113// Decode reads the next YAML-encoded value from its input114// and stores it in the value pointed to by v.115//116// See the documentation for Unmarshal for details about the117// conversion of YAML into a Go value.118func (dec *Decoder) Decode(v interface{}) (err error) {119d := newDecoder()120d.knownFields = dec.knownFields121defer handleErr(&err)122node := dec.parser.parse()123if node == nil {124return io.EOF125}126out := reflect.ValueOf(v)127if out.Kind() == reflect.Ptr && !out.IsNil() {128out = out.Elem()129}130d.unmarshal(node, out)131if len(d.terrors) > 0 {132return &TypeError{d.terrors}133}134return nil135}136137// Decode decodes the node and stores its data into the value pointed to by v.138//139// See the documentation for Unmarshal for details about the140// conversion of YAML into a Go value.141func (n *Node) Decode(v interface{}) (err error) {142d := newDecoder()143defer handleErr(&err)144out := reflect.ValueOf(v)145if out.Kind() == reflect.Ptr && !out.IsNil() {146out = out.Elem()147}148d.unmarshal(n, out)149if len(d.terrors) > 0 {150return &TypeError{d.terrors}151}152return nil153}154155func unmarshal(in []byte, out interface{}, strict bool) (err error) {156defer handleErr(&err)157d := newDecoder()158p := newParser(in)159defer p.destroy()160node := p.parse()161if node != nil {162v := reflect.ValueOf(out)163if v.Kind() == reflect.Ptr && !v.IsNil() {164v = v.Elem()165}166d.unmarshal(node, v)167}168if len(d.terrors) > 0 {169return &TypeError{d.terrors}170}171return nil172}173174// Marshal serializes the value provided into a YAML document. The structure175// of the generated document will reflect the structure of the value itself.176// Maps and pointers (to struct, string, int, etc) are accepted as the in value.177//178// Struct fields are only marshalled if they are exported (have an upper case179// first letter), and are marshalled using the field name lowercased as the180// default key. Custom keys may be defined via the "yaml" name in the field181// tag: the content preceding the first comma is used as the key, and the182// following comma-separated options are used to tweak the marshalling process.183// Conflicting names result in a runtime error.184//185// The field tag format accepted is:186//187// `(...) yaml:"[<key>][,<flag1>[,<flag2>]]" (...)`188//189// The following flags are currently supported:190//191// omitempty Only include the field if it's not set to the zero192// value for the type or to empty slices or maps.193// Zero valued structs will be omitted if all their public194// fields are zero, unless they implement an IsZero195// method (see the IsZeroer interface type), in which196// case the field will be excluded if IsZero returns true.197//198// flow Marshal using a flow style (useful for structs,199// sequences and maps).200//201// inline Inline the field, which must be a struct or a map,202// causing all of its fields or keys to be processed as if203// they were part of the outer struct. For maps, keys must204// not conflict with the yaml keys of other struct fields.205//206// In addition, if the key is "-", the field is ignored.207//208// For example:209//210// type T struct {211// F int `yaml:"a,omitempty"`212// B int213// }214// yaml.Marshal(&T{B: 2}) // Returns "b: 2\n"215// yaml.Marshal(&T{F: 1}} // Returns "a: 1\nb: 0\n"216//217func Marshal(in interface{}) (out []byte, err error) {218defer handleErr(&err)219e := newEncoder()220defer e.destroy()221e.marshalDoc("", reflect.ValueOf(in))222e.finish()223out = e.out224return225}226227// An Encoder writes YAML values to an output stream.228type Encoder struct {229encoder *encoder230}231232// NewEncoder returns a new encoder that writes to w.233// The Encoder should be closed after use to flush all data234// to w.235func NewEncoder(w io.Writer) *Encoder {236return &Encoder{237encoder: newEncoderWithWriter(w),238}239}240241// Encode writes the YAML encoding of v to the stream.242// If multiple items are encoded to the stream, the243// second and subsequent document will be preceded244// with a "---" document separator, but the first will not.245//246// See the documentation for Marshal for details about the conversion of Go247// values to YAML.248func (e *Encoder) Encode(v interface{}) (err error) {249defer handleErr(&err)250e.encoder.marshalDoc("", reflect.ValueOf(v))251return nil252}253254// Encode encodes value v and stores its representation in n.255//256// See the documentation for Marshal for details about the257// conversion of Go values into YAML.258func (n *Node) Encode(v interface{}) (err error) {259defer handleErr(&err)260e := newEncoder()261defer e.destroy()262e.marshalDoc("", reflect.ValueOf(v))263e.finish()264p := newParser(e.out)265p.textless = true266defer p.destroy()267doc := p.parse()268*n = *doc.Content[0]269return nil270}271272// SetIndent changes the used indentation used when encoding.273func (e *Encoder) SetIndent(spaces int) {274if spaces < 0 {275panic("yaml: cannot indent to a negative number of spaces")276}277e.encoder.indent = spaces278}279280// Close closes the encoder by writing any remaining data.281// It does not write a stream terminating string "...".282func (e *Encoder) Close() (err error) {283defer handleErr(&err)284e.encoder.finish()285return nil286}287288func handleErr(err *error) {289if v := recover(); v != nil {290if e, ok := v.(yamlError); ok {291*err = e.err292} else {293panic(v)294}295}296}297298type yamlError struct {299err error300}301302func fail(err error) {303panic(yamlError{err})304}305306func failf(format string, args ...interface{}) {307panic(yamlError{fmt.Errorf("yaml: "+format, args...)})308}309310// A TypeError is returned by Unmarshal when one or more fields in311// the YAML document cannot be properly decoded into the requested312// types. When this error is returned, the value is still313// unmarshaled partially.314type TypeError struct {315Errors []string316}317318func (e *TypeError) Error() string {319return fmt.Sprintf("yaml: unmarshal errors:\n %s", strings.Join(e.Errors, "\n "))320}321322type Kind uint32323324const (325DocumentNode Kind = 1 << iota326SequenceNode327MappingNode328ScalarNode329AliasNode330)331332type Style uint32333334const (335TaggedStyle Style = 1 << iota336DoubleQuotedStyle337SingleQuotedStyle338LiteralStyle339FoldedStyle340FlowStyle341)342343// Node represents an element in the YAML document hierarchy. While documents344// are typically encoded and decoded into higher level types, such as structs345// and maps, Node is an intermediate representation that allows detailed346// control over the content being decoded or encoded.347//348// It's worth noting that although Node offers access into details such as349// line numbers, colums, and comments, the content when re-encoded will not350// have its original textual representation preserved. An effort is made to351// render the data plesantly, and to preserve comments near the data they352// describe, though.353//354// Values that make use of the Node type interact with the yaml package in the355// same way any other type would do, by encoding and decoding yaml data356// directly or indirectly into them.357//358// For example:359//360// var person struct {361// Name string362// Address yaml.Node363// }364// err := yaml.Unmarshal(data, &person)365//366// Or by itself:367//368// var person Node369// err := yaml.Unmarshal(data, &person)370//371type Node struct {372// Kind defines whether the node is a document, a mapping, a sequence,373// a scalar value, or an alias to another node. The specific data type of374// scalar nodes may be obtained via the ShortTag and LongTag methods.375Kind Kind376377// Style allows customizing the apperance of the node in the tree.378Style Style379380// Tag holds the YAML tag defining the data type for the value.381// When decoding, this field will always be set to the resolved tag,382// even when it wasn't explicitly provided in the YAML content.383// When encoding, if this field is unset the value type will be384// implied from the node properties, and if it is set, it will only385// be serialized into the representation if TaggedStyle is used or386// the implicit tag diverges from the provided one.387Tag string388389// Value holds the unescaped and unquoted represenation of the value.390Value string391392// Anchor holds the anchor name for this node, which allows aliases to point to it.393Anchor string394395// Alias holds the node that this alias points to. Only valid when Kind is AliasNode.396Alias *Node397398// Content holds contained nodes for documents, mappings, and sequences.399Content []*Node400401// HeadComment holds any comments in the lines preceding the node and402// not separated by an empty line.403HeadComment string404405// LineComment holds any comments at the end of the line where the node is in.406LineComment string407408// FootComment holds any comments following the node and before empty lines.409FootComment string410411// Line and Column hold the node position in the decoded YAML text.412// These fields are not respected when encoding the node.413Line int414Column int415}416417// IsZero returns whether the node has all of its fields unset.418func (n *Node) IsZero() bool {419return n.Kind == 0 && n.Style == 0 && n.Tag == "" && n.Value == "" && n.Anchor == "" && n.Alias == nil && n.Content == nil &&420n.HeadComment == "" && n.LineComment == "" && n.FootComment == "" && n.Line == 0 && n.Column == 0421}422423424// LongTag returns the long form of the tag that indicates the data type for425// the node. If the Tag field isn't explicitly defined, one will be computed426// based on the node properties.427func (n *Node) LongTag() string {428return longTag(n.ShortTag())429}430431// ShortTag returns the short form of the YAML tag that indicates data type for432// the node. If the Tag field isn't explicitly defined, one will be computed433// based on the node properties.434func (n *Node) ShortTag() string {435if n.indicatedString() {436return strTag437}438if n.Tag == "" || n.Tag == "!" {439switch n.Kind {440case MappingNode:441return mapTag442case SequenceNode:443return seqTag444case AliasNode:445if n.Alias != nil {446return n.Alias.ShortTag()447}448case ScalarNode:449tag, _ := resolve("", n.Value)450return tag451case 0:452// Special case to make the zero value convenient.453if n.IsZero() {454return nullTag455}456}457return ""458}459return shortTag(n.Tag)460}461462func (n *Node) indicatedString() bool {463return n.Kind == ScalarNode &&464(shortTag(n.Tag) == strTag ||465(n.Tag == "" || n.Tag == "!") && n.Style&(SingleQuotedStyle|DoubleQuotedStyle|LiteralStyle|FoldedStyle) != 0)466}467468// SetString is a convenience function that sets the node to a string value469// and defines its style in a pleasant way depending on its content.470func (n *Node) SetString(s string) {471n.Kind = ScalarNode472if utf8.ValidString(s) {473n.Value = s474n.Tag = strTag475} else {476n.Value = encodeBase64(s)477n.Tag = binaryTag478}479if strings.Contains(n.Value, "\n") {480n.Style = LiteralStyle481}482}483484// --------------------------------------------------------------------------485// Maintain a mapping of keys to structure field indexes486487// The code in this section was copied from mgo/bson.488489// structInfo holds details for the serialization of fields of490// a given struct.491type structInfo struct {492FieldsMap map[string]fieldInfo493FieldsList []fieldInfo494495// InlineMap is the number of the field in the struct that496// contains an ,inline map, or -1 if there's none.497InlineMap int498499// InlineUnmarshalers holds indexes to inlined fields that500// contain unmarshaler values.501InlineUnmarshalers [][]int502}503504type fieldInfo struct {505Key string506Num int507OmitEmpty bool508Flow bool509// Id holds the unique field identifier, so we can cheaply510// check for field duplicates without maintaining an extra map.511Id int512513// Inline holds the field index if the field is part of an inlined struct.514Inline []int515}516517var structMap = make(map[reflect.Type]*structInfo)518var fieldMapMutex sync.RWMutex519var unmarshalerType reflect.Type520521func init() {522var v Unmarshaler523unmarshalerType = reflect.ValueOf(&v).Elem().Type()524}525526func getStructInfo(st reflect.Type) (*structInfo, error) {527fieldMapMutex.RLock()528sinfo, found := structMap[st]529fieldMapMutex.RUnlock()530if found {531return sinfo, nil532}533534n := st.NumField()535fieldsMap := make(map[string]fieldInfo)536fieldsList := make([]fieldInfo, 0, n)537inlineMap := -1538inlineUnmarshalers := [][]int(nil)539for i := 0; i != n; i++ {540field := st.Field(i)541if field.PkgPath != "" && !field.Anonymous {542continue // Private field543}544545info := fieldInfo{Num: i}546547tag := field.Tag.Get("yaml")548if tag == "" && strings.Index(string(field.Tag), ":") < 0 {549tag = string(field.Tag)550}551if tag == "-" {552continue553}554555inline := false556fields := strings.Split(tag, ",")557if len(fields) > 1 {558for _, flag := range fields[1:] {559switch flag {560case "omitempty":561info.OmitEmpty = true562case "flow":563info.Flow = true564case "inline":565inline = true566default:567return nil, errors.New(fmt.Sprintf("unsupported flag %q in tag %q of type %s", flag, tag, st))568}569}570tag = fields[0]571}572573if inline {574switch field.Type.Kind() {575case reflect.Map:576if inlineMap >= 0 {577return nil, errors.New("multiple ,inline maps in struct " + st.String())578}579if field.Type.Key() != reflect.TypeOf("") {580return nil, errors.New("option ,inline needs a map with string keys in struct " + st.String())581}582inlineMap = info.Num583case reflect.Struct, reflect.Ptr:584ftype := field.Type585for ftype.Kind() == reflect.Ptr {586ftype = ftype.Elem()587}588if ftype.Kind() != reflect.Struct {589return nil, errors.New("option ,inline may only be used on a struct or map field")590}591if reflect.PtrTo(ftype).Implements(unmarshalerType) {592inlineUnmarshalers = append(inlineUnmarshalers, []int{i})593} else {594sinfo, err := getStructInfo(ftype)595if err != nil {596return nil, err597}598for _, index := range sinfo.InlineUnmarshalers {599inlineUnmarshalers = append(inlineUnmarshalers, append([]int{i}, index...))600}601for _, finfo := range sinfo.FieldsList {602if _, found := fieldsMap[finfo.Key]; found {603msg := "duplicated key '" + finfo.Key + "' in struct " + st.String()604return nil, errors.New(msg)605}606if finfo.Inline == nil {607finfo.Inline = []int{i, finfo.Num}608} else {609finfo.Inline = append([]int{i}, finfo.Inline...)610}611finfo.Id = len(fieldsList)612fieldsMap[finfo.Key] = finfo613fieldsList = append(fieldsList, finfo)614}615}616default:617return nil, errors.New("option ,inline may only be used on a struct or map field")618}619continue620}621622if tag != "" {623info.Key = tag624} else {625info.Key = strings.ToLower(field.Name)626}627628if _, found = fieldsMap[info.Key]; found {629msg := "duplicated key '" + info.Key + "' in struct " + st.String()630return nil, errors.New(msg)631}632633info.Id = len(fieldsList)634fieldsList = append(fieldsList, info)635fieldsMap[info.Key] = info636}637638sinfo = &structInfo{639FieldsMap: fieldsMap,640FieldsList: fieldsList,641InlineMap: inlineMap,642InlineUnmarshalers: inlineUnmarshalers,643}644645fieldMapMutex.Lock()646structMap[st] = sinfo647fieldMapMutex.Unlock()648return sinfo, nil649}650651// IsZeroer is used to check whether an object is zero to652// determine whether it should be omitted when marshaling653// with the omitempty flag. One notable implementation654// is time.Time.655type IsZeroer interface {656IsZero() bool657}658659func isZero(v reflect.Value) bool {660kind := v.Kind()661if z, ok := v.Interface().(IsZeroer); ok {662if (kind == reflect.Ptr || kind == reflect.Interface) && v.IsNil() {663return true664}665return z.IsZero()666}667switch kind {668case reflect.String:669return len(v.String()) == 0670case reflect.Interface, reflect.Ptr:671return v.IsNil()672case reflect.Slice:673return v.Len() == 0674case reflect.Map:675return v.Len() == 0676case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:677return v.Int() == 0678case reflect.Float32, reflect.Float64:679return v.Float() == 0680case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:681return v.Uint() == 0682case reflect.Bool:683return !v.Bool()684case reflect.Struct:685vt := v.Type()686for i := v.NumField() - 1; i >= 0; i-- {687if vt.Field(i).PkgPath != "" {688continue // Private field689}690if !isZero(v.Field(i)) {691return false692}693}694return true695}696return false697}698699700