Path: blob/main/vendor/gopkg.in/yaml.v3/resolve.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/base64"19"math"20"regexp"21"strconv"22"strings"23"time"24)2526type resolveMapItem struct {27value interface{}28tag string29}3031var resolveTable = make([]byte, 256)32var resolveMap = make(map[string]resolveMapItem)3334func init() {35t := resolveTable36t[int('+')] = 'S' // Sign37t[int('-')] = 'S'38for _, c := range "0123456789" {39t[int(c)] = 'D' // Digit40}41for _, c := range "yYnNtTfFoO~" {42t[int(c)] = 'M' // In map43}44t[int('.')] = '.' // Float (potentially in map)4546var resolveMapList = []struct {47v interface{}48tag string49l []string50}{51{true, boolTag, []string{"true", "True", "TRUE"}},52{false, boolTag, []string{"false", "False", "FALSE"}},53{nil, nullTag, []string{"", "~", "null", "Null", "NULL"}},54{math.NaN(), floatTag, []string{".nan", ".NaN", ".NAN"}},55{math.Inf(+1), floatTag, []string{".inf", ".Inf", ".INF"}},56{math.Inf(+1), floatTag, []string{"+.inf", "+.Inf", "+.INF"}},57{math.Inf(-1), floatTag, []string{"-.inf", "-.Inf", "-.INF"}},58{"<<", mergeTag, []string{"<<"}},59}6061m := resolveMap62for _, item := range resolveMapList {63for _, s := range item.l {64m[s] = resolveMapItem{item.v, item.tag}65}66}67}6869const (70nullTag = "!!null"71boolTag = "!!bool"72strTag = "!!str"73intTag = "!!int"74floatTag = "!!float"75timestampTag = "!!timestamp"76seqTag = "!!seq"77mapTag = "!!map"78binaryTag = "!!binary"79mergeTag = "!!merge"80)8182var longTags = make(map[string]string)83var shortTags = make(map[string]string)8485func init() {86for _, stag := range []string{nullTag, boolTag, strTag, intTag, floatTag, timestampTag, seqTag, mapTag, binaryTag, mergeTag} {87ltag := longTag(stag)88longTags[stag] = ltag89shortTags[ltag] = stag90}91}9293const longTagPrefix = "tag:yaml.org,2002:"9495func shortTag(tag string) string {96if strings.HasPrefix(tag, longTagPrefix) {97if stag, ok := shortTags[tag]; ok {98return stag99}100return "!!" + tag[len(longTagPrefix):]101}102return tag103}104105func longTag(tag string) string {106if strings.HasPrefix(tag, "!!") {107if ltag, ok := longTags[tag]; ok {108return ltag109}110return longTagPrefix + tag[2:]111}112return tag113}114115func resolvableTag(tag string) bool {116switch tag {117case "", strTag, boolTag, intTag, floatTag, nullTag, timestampTag:118return true119}120return false121}122123var yamlStyleFloat = regexp.MustCompile(`^[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?$`)124125func resolve(tag string, in string) (rtag string, out interface{}) {126tag = shortTag(tag)127if !resolvableTag(tag) {128return tag, in129}130131defer func() {132switch tag {133case "", rtag, strTag, binaryTag:134return135case floatTag:136if rtag == intTag {137switch v := out.(type) {138case int64:139rtag = floatTag140out = float64(v)141return142case int:143rtag = floatTag144out = float64(v)145return146}147}148}149failf("cannot decode %s `%s` as a %s", shortTag(rtag), in, shortTag(tag))150}()151152// Any data is accepted as a !!str or !!binary.153// Otherwise, the prefix is enough of a hint about what it might be.154hint := byte('N')155if in != "" {156hint = resolveTable[in[0]]157}158if hint != 0 && tag != strTag && tag != binaryTag {159// Handle things we can lookup in a map.160if item, ok := resolveMap[in]; ok {161return item.tag, item.value162}163164// Base 60 floats are a bad idea, were dropped in YAML 1.2, and165// are purposefully unsupported here. They're still quoted on166// the way out for compatibility with other parser, though.167168switch hint {169case 'M':170// We've already checked the map above.171172case '.':173// Not in the map, so maybe a normal float.174floatv, err := strconv.ParseFloat(in, 64)175if err == nil {176return floatTag, floatv177}178179case 'D', 'S':180// Int, float, or timestamp.181// Only try values as a timestamp if the value is unquoted or there's an explicit182// !!timestamp tag.183if tag == "" || tag == timestampTag {184t, ok := parseTimestamp(in)185if ok {186return timestampTag, t187}188}189190plain := strings.Replace(in, "_", "", -1)191intv, err := strconv.ParseInt(plain, 0, 64)192if err == nil {193if intv == int64(int(intv)) {194return intTag, int(intv)195} else {196return intTag, intv197}198}199uintv, err := strconv.ParseUint(plain, 0, 64)200if err == nil {201return intTag, uintv202}203if yamlStyleFloat.MatchString(plain) {204floatv, err := strconv.ParseFloat(plain, 64)205if err == nil {206return floatTag, floatv207}208}209if strings.HasPrefix(plain, "0b") {210intv, err := strconv.ParseInt(plain[2:], 2, 64)211if err == nil {212if intv == int64(int(intv)) {213return intTag, int(intv)214} else {215return intTag, intv216}217}218uintv, err := strconv.ParseUint(plain[2:], 2, 64)219if err == nil {220return intTag, uintv221}222} else if strings.HasPrefix(plain, "-0b") {223intv, err := strconv.ParseInt("-"+plain[3:], 2, 64)224if err == nil {225if true || intv == int64(int(intv)) {226return intTag, int(intv)227} else {228return intTag, intv229}230}231}232// Octals as introduced in version 1.2 of the spec.233// Octals from the 1.1 spec, spelled as 0777, are still234// decoded by default in v3 as well for compatibility.235// May be dropped in v4 depending on how usage evolves.236if strings.HasPrefix(plain, "0o") {237intv, err := strconv.ParseInt(plain[2:], 8, 64)238if err == nil {239if intv == int64(int(intv)) {240return intTag, int(intv)241} else {242return intTag, intv243}244}245uintv, err := strconv.ParseUint(plain[2:], 8, 64)246if err == nil {247return intTag, uintv248}249} else if strings.HasPrefix(plain, "-0o") {250intv, err := strconv.ParseInt("-"+plain[3:], 8, 64)251if err == nil {252if true || intv == int64(int(intv)) {253return intTag, int(intv)254} else {255return intTag, intv256}257}258}259default:260panic("internal error: missing handler for resolver table: " + string(rune(hint)) + " (with " + in + ")")261}262}263return strTag, in264}265266// encodeBase64 encodes s as base64 that is broken up into multiple lines267// as appropriate for the resulting length.268func encodeBase64(s string) string {269const lineLen = 70270encLen := base64.StdEncoding.EncodedLen(len(s))271lines := encLen/lineLen + 1272buf := make([]byte, encLen*2+lines)273in := buf[0:encLen]274out := buf[encLen:]275base64.StdEncoding.Encode(in, []byte(s))276k := 0277for i := 0; i < len(in); i += lineLen {278j := i + lineLen279if j > len(in) {280j = len(in)281}282k += copy(out[k:], in[i:j])283if lines > 1 {284out[k] = '\n'285k++286}287}288return string(out[:k])289}290291// This is a subset of the formats allowed by the regular expression292// defined at http://yaml.org/type/timestamp.html.293var allowedTimestampFormats = []string{294"2006-1-2T15:4:5.999999999Z07:00", // RCF3339Nano with short date fields.295"2006-1-2t15:4:5.999999999Z07:00", // RFC3339Nano with short date fields and lower-case "t".296"2006-1-2 15:4:5.999999999", // space separated with no time zone297"2006-1-2", // date only298// Notable exception: time.Parse cannot handle: "2001-12-14 21:59:43.10 -5"299// from the set of examples.300}301302// parseTimestamp parses s as a timestamp string and303// returns the timestamp and reports whether it succeeded.304// Timestamp formats are defined at http://yaml.org/type/timestamp.html305func parseTimestamp(s string) (time.Time, bool) {306// TODO write code to check all the formats supported by307// http://yaml.org/type/timestamp.html instead of using time.Parse.308309// Quick check: all date formats start with YYYY-.310i := 0311for ; i < len(s); i++ {312if c := s[i]; c < '0' || c > '9' {313break314}315}316if i != 4 || i == len(s) || s[i] != '-' {317return time.Time{}, false318}319for _, format := range allowedTimestampFormats {320if t, err := time.Parse(format, s); err == nil {321return t, true322}323}324return time.Time{}, false325}326327328