Path: blob/main/vendor/go.yaml.in/yaml/v3/encode.go
2872 views
//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.1415package yaml1617import (18"encoding"19"fmt"20"io"21"reflect"22"regexp"23"sort"24"strconv"25"strings"26"time"27"unicode/utf8"28)2930type encoder struct {31emitter yaml_emitter_t32event yaml_event_t33out []byte34flow bool35indent int36doneInit bool37}3839func newEncoder() *encoder {40e := &encoder{}41yaml_emitter_initialize(&e.emitter)42yaml_emitter_set_output_string(&e.emitter, &e.out)43yaml_emitter_set_unicode(&e.emitter, true)44return e45}4647func newEncoderWithWriter(w io.Writer) *encoder {48e := &encoder{}49yaml_emitter_initialize(&e.emitter)50yaml_emitter_set_output_writer(&e.emitter, w)51yaml_emitter_set_unicode(&e.emitter, true)52return e53}5455func (e *encoder) init() {56if e.doneInit {57return58}59if e.indent == 0 {60e.indent = 461}62e.emitter.best_indent = e.indent63yaml_stream_start_event_initialize(&e.event, yaml_UTF8_ENCODING)64e.emit()65e.doneInit = true66}6768func (e *encoder) finish() {69e.emitter.open_ended = false70yaml_stream_end_event_initialize(&e.event)71e.emit()72}7374func (e *encoder) destroy() {75yaml_emitter_delete(&e.emitter)76}7778func (e *encoder) emit() {79// This will internally delete the e.event value.80e.must(yaml_emitter_emit(&e.emitter, &e.event))81}8283func (e *encoder) must(ok bool) {84if !ok {85msg := e.emitter.problem86if msg == "" {87msg = "unknown problem generating YAML content"88}89failf("%s", msg)90}91}9293func (e *encoder) marshalDoc(tag string, in reflect.Value) {94e.init()95var node *Node96if in.IsValid() {97node, _ = in.Interface().(*Node)98}99if node != nil && node.Kind == DocumentNode {100e.nodev(in)101} else {102yaml_document_start_event_initialize(&e.event, nil, nil, true)103e.emit()104e.marshal(tag, in)105yaml_document_end_event_initialize(&e.event, true)106e.emit()107}108}109110func (e *encoder) marshal(tag string, in reflect.Value) {111tag = shortTag(tag)112if !in.IsValid() || in.Kind() == reflect.Ptr && in.IsNil() {113e.nilv()114return115}116iface := in.Interface()117switch value := iface.(type) {118case *Node:119e.nodev(in)120return121case Node:122if !in.CanAddr() {123var n = reflect.New(in.Type()).Elem()124n.Set(in)125in = n126}127e.nodev(in.Addr())128return129case time.Time:130e.timev(tag, in)131return132case *time.Time:133e.timev(tag, in.Elem())134return135case time.Duration:136e.stringv(tag, reflect.ValueOf(value.String()))137return138case Marshaler:139v, err := value.MarshalYAML()140if err != nil {141fail(err)142}143if v == nil {144e.nilv()145return146}147e.marshal(tag, reflect.ValueOf(v))148return149case encoding.TextMarshaler:150text, err := value.MarshalText()151if err != nil {152fail(err)153}154in = reflect.ValueOf(string(text))155case nil:156e.nilv()157return158}159switch in.Kind() {160case reflect.Interface:161e.marshal(tag, in.Elem())162case reflect.Map:163e.mapv(tag, in)164case reflect.Ptr:165e.marshal(tag, in.Elem())166case reflect.Struct:167e.structv(tag, in)168case reflect.Slice, reflect.Array:169e.slicev(tag, in)170case reflect.String:171e.stringv(tag, in)172case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:173e.intv(tag, in)174case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:175e.uintv(tag, in)176case reflect.Float32, reflect.Float64:177e.floatv(tag, in)178case reflect.Bool:179e.boolv(tag, in)180default:181panic("cannot marshal type: " + in.Type().String())182}183}184185func (e *encoder) mapv(tag string, in reflect.Value) {186e.mappingv(tag, func() {187keys := keyList(in.MapKeys())188sort.Sort(keys)189for _, k := range keys {190e.marshal("", k)191e.marshal("", in.MapIndex(k))192}193})194}195196func (e *encoder) fieldByIndex(v reflect.Value, index []int) (field reflect.Value) {197for _, num := range index {198for {199if v.Kind() == reflect.Ptr {200if v.IsNil() {201return reflect.Value{}202}203v = v.Elem()204continue205}206break207}208v = v.Field(num)209}210return v211}212213func (e *encoder) structv(tag string, in reflect.Value) {214sinfo, err := getStructInfo(in.Type())215if err != nil {216panic(err)217}218e.mappingv(tag, func() {219for _, info := range sinfo.FieldsList {220var value reflect.Value221if info.Inline == nil {222value = in.Field(info.Num)223} else {224value = e.fieldByIndex(in, info.Inline)225if !value.IsValid() {226continue227}228}229if info.OmitEmpty && isZero(value) {230continue231}232e.marshal("", reflect.ValueOf(info.Key))233e.flow = info.Flow234e.marshal("", value)235}236if sinfo.InlineMap >= 0 {237m := in.Field(sinfo.InlineMap)238if m.Len() > 0 {239e.flow = false240keys := keyList(m.MapKeys())241sort.Sort(keys)242for _, k := range keys {243if _, found := sinfo.FieldsMap[k.String()]; found {244panic(fmt.Sprintf("cannot have key %q in inlined map: conflicts with struct field", k.String()))245}246e.marshal("", k)247e.flow = false248e.marshal("", m.MapIndex(k))249}250}251}252})253}254255func (e *encoder) mappingv(tag string, f func()) {256implicit := tag == ""257style := yaml_BLOCK_MAPPING_STYLE258if e.flow {259e.flow = false260style = yaml_FLOW_MAPPING_STYLE261}262yaml_mapping_start_event_initialize(&e.event, nil, []byte(tag), implicit, style)263e.emit()264f()265yaml_mapping_end_event_initialize(&e.event)266e.emit()267}268269func (e *encoder) slicev(tag string, in reflect.Value) {270implicit := tag == ""271style := yaml_BLOCK_SEQUENCE_STYLE272if e.flow {273e.flow = false274style = yaml_FLOW_SEQUENCE_STYLE275}276e.must(yaml_sequence_start_event_initialize(&e.event, nil, []byte(tag), implicit, style))277e.emit()278n := in.Len()279for i := 0; i < n; i++ {280e.marshal("", in.Index(i))281}282e.must(yaml_sequence_end_event_initialize(&e.event))283e.emit()284}285286// isBase60 returns whether s is in base 60 notation as defined in YAML 1.1.287//288// The base 60 float notation in YAML 1.1 is a terrible idea and is unsupported289// in YAML 1.2 and by this package, but these should be marshalled quoted for290// the time being for compatibility with other parsers.291func isBase60Float(s string) (result bool) {292// Fast path.293if s == "" {294return false295}296c := s[0]297if !(c == '+' || c == '-' || c >= '0' && c <= '9') || strings.IndexByte(s, ':') < 0 {298return false299}300// Do the full match.301return base60float.MatchString(s)302}303304// From http://yaml.org/type/float.html, except the regular expression there305// is bogus. In practice parsers do not enforce the "\.[0-9_]*" suffix.306var base60float = regexp.MustCompile(`^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+(?:\.[0-9_]*)?$`)307308// isOldBool returns whether s is bool notation as defined in YAML 1.1.309//310// We continue to force strings that YAML 1.1 would interpret as booleans to be311// rendered as quotes strings so that the marshalled output valid for YAML 1.1312// parsing.313func isOldBool(s string) (result bool) {314switch s {315case "y", "Y", "yes", "Yes", "YES", "on", "On", "ON",316"n", "N", "no", "No", "NO", "off", "Off", "OFF":317return true318default:319return false320}321}322323func (e *encoder) stringv(tag string, in reflect.Value) {324var style yaml_scalar_style_t325s := in.String()326canUsePlain := true327switch {328case !utf8.ValidString(s):329if tag == binaryTag {330failf("explicitly tagged !!binary data must be base64-encoded")331}332if tag != "" {333failf("cannot marshal invalid UTF-8 data as %s", shortTag(tag))334}335// It can't be encoded directly as YAML so use a binary tag336// and encode it as base64.337tag = binaryTag338s = encodeBase64(s)339case tag == "":340// Check to see if it would resolve to a specific341// tag when encoded unquoted. If it doesn't,342// there's no need to quote it.343rtag, _ := resolve("", s)344canUsePlain = rtag == strTag && !(isBase60Float(s) || isOldBool(s))345}346// Note: it's possible for user code to emit invalid YAML347// if they explicitly specify a tag and a string containing348// text that's incompatible with that tag.349switch {350case strings.Contains(s, "\n"):351if e.flow {352style = yaml_DOUBLE_QUOTED_SCALAR_STYLE353} else {354style = yaml_LITERAL_SCALAR_STYLE355}356case canUsePlain:357style = yaml_PLAIN_SCALAR_STYLE358default:359style = yaml_DOUBLE_QUOTED_SCALAR_STYLE360}361e.emitScalar(s, "", tag, style, nil, nil, nil, nil)362}363364func (e *encoder) boolv(tag string, in reflect.Value) {365var s string366if in.Bool() {367s = "true"368} else {369s = "false"370}371e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil)372}373374func (e *encoder) intv(tag string, in reflect.Value) {375s := strconv.FormatInt(in.Int(), 10)376e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil)377}378379func (e *encoder) uintv(tag string, in reflect.Value) {380s := strconv.FormatUint(in.Uint(), 10)381e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil)382}383384func (e *encoder) timev(tag string, in reflect.Value) {385t := in.Interface().(time.Time)386s := t.Format(time.RFC3339Nano)387e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil)388}389390func (e *encoder) floatv(tag string, in reflect.Value) {391// Issue #352: When formatting, use the precision of the underlying value392precision := 64393if in.Kind() == reflect.Float32 {394precision = 32395}396397s := strconv.FormatFloat(in.Float(), 'g', -1, precision)398switch s {399case "+Inf":400s = ".inf"401case "-Inf":402s = "-.inf"403case "NaN":404s = ".nan"405}406e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil)407}408409func (e *encoder) nilv() {410e.emitScalar("null", "", "", yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil)411}412413func (e *encoder) emitScalar(value, anchor, tag string, style yaml_scalar_style_t, head, line, foot, tail []byte) {414// TODO Kill this function. Replace all initialize calls by their underlining Go literals.415implicit := tag == ""416if !implicit {417tag = longTag(tag)418}419e.must(yaml_scalar_event_initialize(&e.event, []byte(anchor), []byte(tag), []byte(value), implicit, implicit, style))420e.event.head_comment = head421e.event.line_comment = line422e.event.foot_comment = foot423e.event.tail_comment = tail424e.emit()425}426427func (e *encoder) nodev(in reflect.Value) {428e.node(in.Interface().(*Node), "")429}430431func (e *encoder) node(node *Node, tail string) {432// Zero nodes behave as nil.433if node.Kind == 0 && node.IsZero() {434e.nilv()435return436}437438// If the tag was not explicitly requested, and dropping it won't change the439// implicit tag of the value, don't include it in the presentation.440var tag = node.Tag441var stag = shortTag(tag)442var forceQuoting bool443if tag != "" && node.Style&TaggedStyle == 0 {444if node.Kind == ScalarNode {445if stag == strTag && node.Style&(SingleQuotedStyle|DoubleQuotedStyle|LiteralStyle|FoldedStyle) != 0 {446tag = ""447} else {448rtag, _ := resolve("", node.Value)449if rtag == stag {450tag = ""451} else if stag == strTag {452tag = ""453forceQuoting = true454}455}456} else {457var rtag string458switch node.Kind {459case MappingNode:460rtag = mapTag461case SequenceNode:462rtag = seqTag463}464if rtag == stag {465tag = ""466}467}468}469470switch node.Kind {471case DocumentNode:472yaml_document_start_event_initialize(&e.event, nil, nil, true)473e.event.head_comment = []byte(node.HeadComment)474e.emit()475for _, node := range node.Content {476e.node(node, "")477}478yaml_document_end_event_initialize(&e.event, true)479e.event.foot_comment = []byte(node.FootComment)480e.emit()481482case SequenceNode:483style := yaml_BLOCK_SEQUENCE_STYLE484if node.Style&FlowStyle != 0 {485style = yaml_FLOW_SEQUENCE_STYLE486}487e.must(yaml_sequence_start_event_initialize(&e.event, []byte(node.Anchor), []byte(longTag(tag)), tag == "", style))488e.event.head_comment = []byte(node.HeadComment)489e.emit()490for _, node := range node.Content {491e.node(node, "")492}493e.must(yaml_sequence_end_event_initialize(&e.event))494e.event.line_comment = []byte(node.LineComment)495e.event.foot_comment = []byte(node.FootComment)496e.emit()497498case MappingNode:499style := yaml_BLOCK_MAPPING_STYLE500if node.Style&FlowStyle != 0 {501style = yaml_FLOW_MAPPING_STYLE502}503yaml_mapping_start_event_initialize(&e.event, []byte(node.Anchor), []byte(longTag(tag)), tag == "", style)504e.event.tail_comment = []byte(tail)505e.event.head_comment = []byte(node.HeadComment)506e.emit()507508// The tail logic below moves the foot comment of prior keys to the following key,509// since the value for each key may be a nested structure and the foot needs to be510// processed only the entirety of the value is streamed. The last tail is processed511// with the mapping end event.512var tail string513for i := 0; i+1 < len(node.Content); i += 2 {514k := node.Content[i]515foot := k.FootComment516if foot != "" {517kopy := *k518kopy.FootComment = ""519k = &kopy520}521e.node(k, tail)522tail = foot523524v := node.Content[i+1]525e.node(v, "")526}527528yaml_mapping_end_event_initialize(&e.event)529e.event.tail_comment = []byte(tail)530e.event.line_comment = []byte(node.LineComment)531e.event.foot_comment = []byte(node.FootComment)532e.emit()533534case AliasNode:535yaml_alias_event_initialize(&e.event, []byte(node.Value))536e.event.head_comment = []byte(node.HeadComment)537e.event.line_comment = []byte(node.LineComment)538e.event.foot_comment = []byte(node.FootComment)539e.emit()540541case ScalarNode:542value := node.Value543if !utf8.ValidString(value) {544if stag == binaryTag {545failf("explicitly tagged !!binary data must be base64-encoded")546}547if stag != "" {548failf("cannot marshal invalid UTF-8 data as %s", stag)549}550// It can't be encoded directly as YAML so use a binary tag551// and encode it as base64.552tag = binaryTag553value = encodeBase64(value)554}555556style := yaml_PLAIN_SCALAR_STYLE557switch {558case node.Style&DoubleQuotedStyle != 0:559style = yaml_DOUBLE_QUOTED_SCALAR_STYLE560case node.Style&SingleQuotedStyle != 0:561style = yaml_SINGLE_QUOTED_SCALAR_STYLE562case node.Style&LiteralStyle != 0:563style = yaml_LITERAL_SCALAR_STYLE564case node.Style&FoldedStyle != 0:565style = yaml_FOLDED_SCALAR_STYLE566case strings.Contains(value, "\n"):567style = yaml_LITERAL_SCALAR_STYLE568case forceQuoting:569style = yaml_DOUBLE_QUOTED_SCALAR_STYLE570}571572e.emitScalar(value, node.Anchor, tag, style, []byte(node.HeadComment), []byte(node.LineComment), []byte(node.FootComment), []byte(tail))573default:574failf("cannot encode node with unknown kind %d", node.Kind)575}576}577578579