pax_global_header00006660000000000000000000000064142477460410014523gustar00rootroot0000000000000052 comment=16b11cef0cfe0284910f5628c1e65c73998d359d yaml-0.2.0/000077500000000000000000000000001424774604100124645ustar00rootroot00000000000000yaml-0.2.0/.github/000077500000000000000000000000001424774604100140245ustar00rootroot00000000000000yaml-0.2.0/.github/workflows/000077500000000000000000000000001424774604100160615ustar00rootroot00000000000000yaml-0.2.0/.github/workflows/lint.yaml000066400000000000000000000005151424774604100177140ustar00rootroot00000000000000name: Lint on: push: tags: - v* branches: - main pull_request: jobs: lint: name: golangci-lint runs-on: ubuntu-latest steps: - name: Check out code uses: actions/checkout@v2 - name: Lint uses: golangci/golangci-lint-action@v2 with: version: v1.46 yaml-0.2.0/.github/workflows/release.yaml000066400000000000000000000010301424774604100203570ustar00rootroot00000000000000# # Automatically tag a merge with main # name: Release on: push: branches: - main jobs: tag-build-publish: name: Tag runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v2 with: fetch-depth: "0" # make sure we get all commits! - name: Bump version and push tag id: bump uses: anothrNick/github-tag-action@1.36.0 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} RELEASE_BRANCHES: main WITH_V: true yaml-0.2.0/.github/workflows/test.yaml000066400000000000000000000010771424774604100177310ustar00rootroot00000000000000name: Test Go on: [push, pull_request] jobs: lint-test-build: name: Lint, Test runs-on: ubuntu-latest strategy: matrix: go: ["1.14", "1.15", "1.16", "1.17", "1.18"] steps: - name: Check out code uses: actions/checkout@v3 - name: Set up Go uses: actions/setup-go@v3 with: go-version: ${{ matrix.go }} id: go - name: Install Dependencies env: GOPROXY: https://proxy.golang.org,direct run: go mod download - name: Test run: go test -race ./... yaml-0.2.0/.gitignore000066400000000000000000000003501424774604100144520ustar00rootroot00000000000000# OSX leaves these everywhere on SMB shares ._* # Eclipse files .classpath .project .settings/** # Emacs save files *~ # Vim-related files [._]*.s[a-w][a-z] [._]s[a-w][a-z] *.un~ Session.vim .netrwhist # Go test binaries *.test yaml-0.2.0/.golangci.toml000066400000000000000000000005001424774604100152150ustar00rootroot00000000000000[run] timeout = "120s" [output] format = "colored-line-number" [linters] enable = [ "gocyclo", "unconvert", "goimports", "unused", "varcheck", "vetshadow", "misspell", "nakedret", "errcheck", "revive", "ineffassign", "deadcode", "goconst", "vet", "unparam", "gofmt" ] [issues] exclude-use-default = false yaml-0.2.0/LICENSE000066400000000000000000000047751424774604100135060ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2014 Sam Ghods Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Copyright (c) 2012 The Go Authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. yaml-0.2.0/README.md000066400000000000000000000073461424774604100137550ustar00rootroot00000000000000# YAML marshaling and unmarshaling support for Go [![Lint](https://github.com/invopop/yaml/actions/workflows/lint.yaml/badge.svg)](https://github.com/invopop/yaml/actions/workflows/lint.yaml) [![Test Go](https://github.com/invopop/yaml/actions/workflows/test.yaml/badge.svg)](https://github.com/invopop/yaml/actions/workflows/test.yaml) [![Go Report Card](https://goreportcard.com/badge/github.com/invopop/yaml)](https://goreportcard.com/report/github.com/invopop/yaml) ![Latest Tag](https://img.shields.io/github/v/tag/invopop/yaml) ## Introduction A wrapper around [go-yaml](https://github.com/go-yaml/yaml) designed to enable a better way of handling YAML when marshaling to and from structs. This is a fork and split of the original [ghodss/yaml](https://github.com/ghodss/yaml) repository which no longer appears to be maintained. In short, this library first converts YAML to JSON using go-yaml and then uses `json.Marshal` and `json.Unmarshal` to convert to or from the struct. This means that it effectively reuses the JSON struct tags as well as the custom JSON methods `MarshalJSON` and `UnmarshalJSON` unlike go-yaml. For a detailed overview of the rationale behind this method, [see this blog post](https://web.archive.org/web/20150812020634/http://ghodss.com/2014/the-right-way-to-handle-yaml-in-golang/). ## Compatibility This package uses [go-yaml](https://github.com/go-yaml/yaml) and therefore supports [everything go-yaml supports](https://github.com/go-yaml/yaml#compatibility). Tested against Go versions 1.14 and onwards. ## Caveats **Caveat #1:** When using `yaml.Marshal` and `yaml.Unmarshal`, binary data should NOT be preceded with the `!!binary` YAML tag. If you do, go-yaml will convert the binary data from base64 to native binary data, which is not compatible with JSON. You can still use binary in your YAML files though - just store them without the `!!binary` tag and decode the base64 in your code (e.g. in the custom JSON methods `MarshalJSON` and `UnmarshalJSON`). This also has the benefit that your YAML and your JSON binary data will be decoded exactly the same way. As an example: ``` BAD: exampleKey: !!binary gIGC GOOD: exampleKey: gIGC ... and decode the base64 data in your code. ``` **Caveat #2:** When using `YAMLToJSON` directly, maps with keys that are maps will result in an error since this is not supported by JSON. This error will occur in `Unmarshal` as well since you can't unmarshal map keys anyways since struct fields can't be keys. ## Installation and usage To install, run: ``` $ go get github.com/invopop/yaml ``` And import using: ``` import "github.com/invopop/yaml" ``` Usage is very similar to the JSON library: ```go package main import ( "fmt" "github.com/invopop/yaml" ) type Person struct { Name string `json:"name"` // Affects YAML field names too. Age int `json:"age"` } func main() { // Marshal a Person struct to YAML. p := Person{"John", 30} y, err := yaml.Marshal(p) if err != nil { fmt.Printf("err: %v\n", err) return } fmt.Println(string(y)) /* Output: age: 30 name: John */ // Unmarshal the YAML back into a Person struct. var p2 Person err = yaml.Unmarshal(y, &p2) if err != nil { fmt.Printf("err: %v\n", err) return } fmt.Println(p2) /* Output: {John 30} */ } ``` `yaml.YAMLToJSON` and `yaml.JSONToYAML` methods are also available: ```go package main import ( "fmt" "github.com/invopop/yaml" ) func main() { j := []byte(`{"name": "John", "age": 30}`) y, err := yaml.JSONToYAML(j) if err != nil { fmt.Printf("err: %v\n", err) return } fmt.Println(string(y)) /* Output: name: John age: 30 */ j2, err := yaml.YAMLToJSON(y) if err != nil { fmt.Printf("err: %v\n", err) return } fmt.Println(string(j2)) /* Output: {"age":30,"name":"John"} */ } ``` yaml-0.2.0/fields.go000066400000000000000000000305761424774604100142740ustar00rootroot00000000000000// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package yaml import ( "bytes" "encoding" "encoding/json" "reflect" "sort" "strings" "sync" "unicode" "unicode/utf8" ) // indirect walks down v allocating pointers as needed, // until it gets to a non-pointer. // if it encounters an Unmarshaler, indirect stops and returns that. // if decodingNull is true, indirect stops at the last pointer so it can be set to nil. func indirect(v reflect.Value, decodingNull bool) (json.Unmarshaler, encoding.TextUnmarshaler, reflect.Value) { // If v is a named type and is addressable, // start with its address, so that if the type has pointer methods, // we find them. if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() { v = v.Addr() } for { // Load value from interface, but only if the result will be // usefully addressable. if v.Kind() == reflect.Interface && !v.IsNil() { e := v.Elem() if e.Kind() == reflect.Ptr && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Ptr) { v = e continue } } if v.Kind() != reflect.Ptr { break } if v.Elem().Kind() != reflect.Ptr && decodingNull && v.CanSet() { break } if v.IsNil() { if v.CanSet() { v.Set(reflect.New(v.Type().Elem())) } else { v = reflect.New(v.Type().Elem()) } } if v.Type().NumMethod() > 0 { if u, ok := v.Interface().(json.Unmarshaler); ok { return u, nil, reflect.Value{} } if u, ok := v.Interface().(encoding.TextUnmarshaler); ok { return nil, u, reflect.Value{} } } v = v.Elem() } return nil, nil, v } // A field represents a single field found in a struct. type field struct { name string nameBytes []byte // []byte(name) equalFold func(s, t []byte) bool // bytes.EqualFold or equivalent tag bool index []int typ reflect.Type omitEmpty bool quoted bool } func fillField(f field) field { f.nameBytes = []byte(f.name) f.equalFold = foldFunc(f.nameBytes) return f } // byName sorts field by name, breaking ties with depth, // then breaking ties with "name came from json tag", then // breaking ties with index sequence. type byName []field func (x byName) Len() int { return len(x) } func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] } func (x byName) Less(i, j int) bool { if x[i].name != x[j].name { return x[i].name < x[j].name } if len(x[i].index) != len(x[j].index) { return len(x[i].index) < len(x[j].index) } if x[i].tag != x[j].tag { return x[i].tag } return byIndex(x).Less(i, j) } // byIndex sorts field by index sequence. type byIndex []field func (x byIndex) Len() int { return len(x) } func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] } func (x byIndex) Less(i, j int) bool { for k, xik := range x[i].index { if k >= len(x[j].index) { return false } if xik != x[j].index[k] { return xik < x[j].index[k] } } return len(x[i].index) < len(x[j].index) } // typeFields returns a list of fields that JSON should recognize for the given type. // The algorithm is breadth-first search over the set of structs to include - the top struct // and then any reachable anonymous structs. func typeFields(t reflect.Type) []field { // Anonymous fields to explore at the current level and the next. current := []field{} next := []field{{typ: t}} // Count of queued names for current level and the next. var count, nextCount map[reflect.Type]int // Types already visited at an earlier level. visited := map[reflect.Type]bool{} // Fields found. var fields []field for len(next) > 0 { current, next = next, current[:0] count, nextCount = nextCount, map[reflect.Type]int{} for _, f := range current { if visited[f.typ] { continue } visited[f.typ] = true // Scan f.typ for fields to include. for i := 0; i < f.typ.NumField(); i++ { sf := f.typ.Field(i) if sf.PkgPath != "" { // unexported continue } tag := sf.Tag.Get("json") if tag == "-" { continue } name, opts := parseTag(tag) if !isValidTag(name) { name = "" } index := make([]int, len(f.index)+1) copy(index, f.index) index[len(f.index)] = i ft := sf.Type if ft.Name() == "" && ft.Kind() == reflect.Ptr { // Follow pointer. ft = ft.Elem() } // Record found field and index sequence. if name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct { tagged := name != "" if name == "" { name = sf.Name } fields = append(fields, fillField(field{ name: name, tag: tagged, index: index, typ: ft, omitEmpty: opts.Contains("omitempty"), quoted: opts.Contains("string"), })) if count[f.typ] > 1 { // If there were multiple instances, add a second, // so that the annihilation code will see a duplicate. // It only cares about the distinction between 1 or 2, // so don't bother generating any more copies. fields = append(fields, fields[len(fields)-1]) } continue } // Record new anonymous struct to explore in next round. nextCount[ft]++ if nextCount[ft] == 1 { next = append(next, fillField(field{name: ft.Name(), index: index, typ: ft})) } } } } sort.Sort(byName(fields)) // Delete all fields that are hidden by the Go rules for embedded fields, // except that fields with JSON tags are promoted. // The fields are sorted in primary order of name, secondary order // of field index length. Loop over names; for each name, delete // hidden fields by choosing the one dominant field that survives. out := fields[:0] for advance, i := 0, 0; i < len(fields); i += advance { // One iteration per name. // Find the sequence of fields with the name of this first field. fi := fields[i] name := fi.name for advance = 1; i+advance < len(fields); advance++ { fj := fields[i+advance] if fj.name != name { break } } if advance == 1 { // Only one field with this name out = append(out, fi) continue } dominant, ok := dominantField(fields[i : i+advance]) if ok { out = append(out, dominant) } } fields = out sort.Sort(byIndex(fields)) return fields } // dominantField looks through the fields, all of which are known to // have the same name, to find the single field that dominates the // others using Go's embedding rules, modified by the presence of // JSON tags. If there are multiple top-level fields, the boolean // will be false: This condition is an error in Go and we skip all // the fields. func dominantField(fields []field) (field, bool) { // The fields are sorted in increasing index-length order. The winner // must therefore be one with the shortest index length. Drop all // longer entries, which is easy: just truncate the slice. length := len(fields[0].index) tagged := -1 // Index of first tagged field. for i, f := range fields { if len(f.index) > length { fields = fields[:i] break } if f.tag { if tagged >= 0 { // Multiple tagged fields at the same level: conflict. // Return no field. return field{}, false } tagged = i } } if tagged >= 0 { return fields[tagged], true } // All remaining fields have the same length. If there's more than one, // we have a conflict (two fields named "X" at the same level) and we // return no field. if len(fields) > 1 { return field{}, false } return fields[0], true } var fieldCache struct { sync.RWMutex m map[reflect.Type][]field } // cachedTypeFields is like typeFields but uses a cache to avoid repeated work. func cachedTypeFields(t reflect.Type) []field { fieldCache.RLock() f := fieldCache.m[t] fieldCache.RUnlock() if f != nil { return f } // Compute fields without lock. // Might duplicate effort but won't hold other computations back. f = typeFields(t) if f == nil { f = []field{} } fieldCache.Lock() if fieldCache.m == nil { fieldCache.m = map[reflect.Type][]field{} } fieldCache.m[t] = f fieldCache.Unlock() return f } func isValidTag(s string) bool { if s == "" { return false } for _, c := range s { switch { case strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", c): // Backslash and quote chars are reserved, but // otherwise any punctuation chars are allowed // in a tag name. default: if !unicode.IsLetter(c) && !unicode.IsDigit(c) { return false } } } return true } const ( caseMask = ^byte(0x20) // Mask to ignore case in ASCII. kelvin = '\u212a' smallLongEss = '\u017f' ) // foldFunc returns one of four different case folding equivalence // functions, from most general (and slow) to fastest: // // 1) bytes.EqualFold, if the key s contains any non-ASCII UTF-8 // 2) equalFoldRight, if s contains special folding ASCII ('k', 'K', 's', 'S') // 3) asciiEqualFold, no special, but includes non-letters (including _) // 4) simpleLetterEqualFold, no specials, no non-letters. // // The letters S and K are special because they map to 3 runes, not just 2: // * S maps to s and to U+017F 'ſ' Latin small letter long s // * k maps to K and to U+212A 'K' Kelvin sign // See http://play.golang.org/p/tTxjOc0OGo // // The returned function is specialized for matching against s and // should only be given s. It's not curried for performance reasons. func foldFunc(s []byte) func(s, t []byte) bool { nonLetter := false special := false // special letter for _, b := range s { if b >= utf8.RuneSelf { return bytes.EqualFold } upper := b & caseMask if upper < 'A' || upper > 'Z' { nonLetter = true } else if upper == 'K' || upper == 'S' { // See above for why these letters are special. special = true } } if special { return equalFoldRight } if nonLetter { return asciiEqualFold } return simpleLetterEqualFold } // equalFoldRight is a specialization of bytes.EqualFold when s is // known to be all ASCII (including punctuation), but contains an 's', // 'S', 'k', or 'K', requiring a Unicode fold on the bytes in t. // See comments on foldFunc. func equalFoldRight(s, t []byte) bool { for _, sb := range s { if len(t) == 0 { return false } tb := t[0] if tb < utf8.RuneSelf { if sb != tb { sbUpper := sb & caseMask if 'A' <= sbUpper && sbUpper <= 'Z' { if sbUpper != tb&caseMask { return false } } else { return false } } t = t[1:] continue } // sb is ASCII and t is not. t must be either kelvin // sign or long s; sb must be s, S, k, or K. tr, size := utf8.DecodeRune(t) switch sb { case 's', 'S': if tr != smallLongEss { return false } case 'k', 'K': if tr != kelvin { return false } default: return false } t = t[size:] } return len(t) <= 0 } // asciiEqualFold is a specialization of bytes.EqualFold for use when // s is all ASCII (but may contain non-letters) and contains no // special-folding letters. // See comments on foldFunc. func asciiEqualFold(s, t []byte) bool { if len(s) != len(t) { return false } for i, sb := range s { tb := t[i] if sb == tb { continue } if ('a' <= sb && sb <= 'z') || ('A' <= sb && sb <= 'Z') { if sb&caseMask != tb&caseMask { return false } } else { return false } } return true } // simpleLetterEqualFold is a specialization of bytes.EqualFold for // use when s is all ASCII letters (no underscores, etc) and also // doesn't contain 'k', 'K', 's', or 'S'. // See comments on foldFunc. func simpleLetterEqualFold(s, t []byte) bool { if len(s) != len(t) { return false } for i, b := range s { if b&caseMask != t[i]&caseMask { return false } } return true } // tagOptions is the string following a comma in a struct field's "json" // tag, or the empty string. It does not include the leading comma. type tagOptions string // parseTag splits a struct field's json tag into its name and // comma-separated options. func parseTag(tag string) (string, tagOptions) { if idx := strings.Index(tag, ","); idx != -1 { return tag[:idx], tagOptions(tag[idx+1:]) } return tag, tagOptions("") } // Contains reports whether a comma-separated list of options // contains a particular substr flag. substr must be surrounded by a // string boundary or commas. func (o tagOptions) Contains(optionName string) bool { if len(o) == 0 { return false } s := string(o) for s != "" { var next string i := strings.Index(s, ",") if i >= 0 { s, next = s[:i], s[i+1:] } if s == optionName { return true } s = next } return false } yaml-0.2.0/go.mod000066400000000000000000000001111424774604100135630ustar00rootroot00000000000000module github.com/invopop/yaml go 1.14 require gopkg.in/yaml.v3 v3.0.0 yaml-0.2.0/go.sum000066400000000000000000000005501424774604100136170ustar00rootroot00000000000000gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0 h1:hjy8E9ON/egN1tAYqKb61G10WtihqetD4sz2H+8nIeA= gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= yaml-0.2.0/yaml.go000066400000000000000000000237751424774604100137730ustar00rootroot00000000000000// Package yaml provides a wrapper around go-yaml designed to enable a better // way of handling YAML when marshaling to and from structs. // // In short, this package first converts YAML to JSON using go-yaml and then // uses json.Marshal and json.Unmarshal to convert to or from the struct. This // means that it effectively reuses the JSON struct tags as well as the custom // JSON methods MarshalJSON and UnmarshalJSON unlike go-yaml. // package yaml // import "github.com/invopop/yaml" import ( "bytes" "encoding/json" "errors" "fmt" "io" "reflect" "strconv" "gopkg.in/yaml.v3" ) // Marshal the object into JSON then converts JSON to YAML and returns the // YAML. func Marshal(o interface{}) ([]byte, error) { j, err := json.Marshal(o) if err != nil { return nil, fmt.Errorf("error marshaling into JSON: %v", err) } y, err := JSONToYAML(j) if err != nil { return nil, fmt.Errorf("error converting JSON to YAML: %v", err) } return y, nil } // JSONOpt is a decoding option for decoding from JSON format. type JSONOpt func(*json.Decoder) *json.Decoder // Unmarshal converts YAML to JSON then uses JSON to unmarshal into an object, // optionally configuring the behavior of the JSON unmarshal. func Unmarshal(y []byte, o interface{}, opts ...JSONOpt) error { dec := yaml.NewDecoder(bytes.NewReader(y)) return unmarshal(dec, o, opts) } func unmarshal(dec *yaml.Decoder, o interface{}, opts []JSONOpt) error { vo := reflect.ValueOf(o) j, err := yamlToJSON(dec, &vo) if err != nil { return fmt.Errorf("error converting YAML to JSON: %v", err) } err = jsonUnmarshal(bytes.NewReader(j), o, opts...) if err != nil { return fmt.Errorf("error unmarshaling JSON: %v", err) } return nil } // jsonUnmarshal unmarshals the JSON byte stream from the given reader into the // object, optionally applying decoder options prior to decoding. We are not // using json.Unmarshal directly as we want the chance to pass in non-default // options. func jsonUnmarshal(r io.Reader, o interface{}, opts ...JSONOpt) error { d := json.NewDecoder(r) for _, opt := range opts { d = opt(d) } if err := d.Decode(&o); err != nil { return fmt.Errorf("while decoding JSON: %v", err) } return nil } // JSONToYAML converts JSON to YAML. func JSONToYAML(j []byte) ([]byte, error) { // Convert the JSON to an object. var jsonObj interface{} // We are using yaml.Unmarshal here (instead of json.Unmarshal) because the // Go JSON library doesn't try to pick the right number type (int, float, // etc.) when unmarshalling to interface{}, it just picks float64 // universally. go-yaml does go through the effort of picking the right // number type, so we can preserve number type throughout this process. err := yaml.Unmarshal(j, &jsonObj) if err != nil { return nil, err } // Marshal this object into YAML. return yaml.Marshal(jsonObj) } // YAMLToJSON converts YAML to JSON. Since JSON is a subset of YAML, // passing JSON through this method should be a no-op. // // Things YAML can do that are not supported by JSON: // * In YAML you can have binary and null keys in your maps. These are invalid // in JSON. (int and float keys are converted to strings.) // * Binary data in YAML with the !!binary tag is not supported. If you want to // use binary data with this library, encode the data as base64 as usual but do // not use the !!binary tag in your YAML. This will ensure the original base64 // encoded data makes it all the way through to the JSON. // func YAMLToJSON(y []byte) ([]byte, error) { //nolint:revive dec := yaml.NewDecoder(bytes.NewReader(y)) return yamlToJSON(dec, nil) } func yamlToJSON(dec *yaml.Decoder, jsonTarget *reflect.Value) ([]byte, error) { // Convert the YAML to an object. var yamlObj interface{} if err := dec.Decode(&yamlObj); err != nil { // Functionality changed in v3 which means we need to ignore EOF error. // See https://github.com/go-yaml/yaml/issues/639 if !errors.Is(err, io.EOF) { return nil, err } } // YAML objects are not completely compatible with JSON objects (e.g. you // can have non-string keys in YAML). So, convert the YAML-compatible object // to a JSON-compatible object, failing with an error if irrecoverable // incompatibilities happen along the way. jsonObj, err := convertToJSONableObject(yamlObj, jsonTarget) if err != nil { return nil, err } // Convert this object to JSON and return the data. return json.Marshal(jsonObj) } func convertToJSONableObject(yamlObj interface{}, jsonTarget *reflect.Value) (interface{}, error) { //nolint:gocyclo var err error // Resolve jsonTarget to a concrete value (i.e. not a pointer or an // interface). We pass decodingNull as false because we're not actually // decoding into the value, we're just checking if the ultimate target is a // string. if jsonTarget != nil { ju, tu, pv := indirect(*jsonTarget, false) // We have a JSON or Text Umarshaler at this level, so we can't be trying // to decode into a string. if ju != nil || tu != nil { jsonTarget = nil } else { jsonTarget = &pv } } // go-yaml v3 changed from v2 and now will provide map[string]interface{} by // default and map[interface{}]interface{} when none of the keys strings. // To get around this, we run a pre-loop to convert the map. // JSON only supports strings as keys, so we must convert. switch typedYAMLObj := yamlObj.(type) { case map[interface{}]interface{}: // From my reading of go-yaml v2 (specifically the resolve function), // keys can only have the types string, int, int64, float64, binary // (unsupported), or null (unsupported). strMap := make(map[string]interface{}) for k, v := range typedYAMLObj { // Resolve the key to a string first. var keyString string switch typedKey := k.(type) { case string: keyString = typedKey case int: keyString = strconv.Itoa(typedKey) case int64: // go-yaml will only return an int64 as a key if the system // architecture is 32-bit and the key's value is between 32-bit // and 64-bit. Otherwise the key type will simply be int. keyString = strconv.FormatInt(typedKey, 10) case float64: // Float64 is now supported in keys keyString = strconv.FormatFloat(typedKey, 'g', -1, 64) case bool: if typedKey { keyString = "true" } else { keyString = "false" } default: return nil, fmt.Errorf("unsupported map key of type: %s, key: %+#v, value: %+#v", reflect.TypeOf(k), k, v) } strMap[keyString] = v } // replace yamlObj with our new string map yamlObj = strMap } // If yamlObj is a number or a boolean, check if jsonTarget is a string - // if so, coerce. Else return normal. // If yamlObj is a map or array, find the field that each key is // unmarshaling to, and when you recurse pass the reflect.Value for that // field back into this function. switch typedYAMLObj := yamlObj.(type) { case map[string]interface{}: for k, v := range typedYAMLObj { // jsonTarget should be a struct or a map. If it's a struct, find // the field it's going to map to and pass its reflect.Value. If // it's a map, find the element type of the map and pass the // reflect.Value created from that type. If it's neither, just pass // nil - JSON conversion will error for us if it's a real issue. if jsonTarget != nil { t := *jsonTarget if t.Kind() == reflect.Struct { keyBytes := []byte(k) // Find the field that the JSON library would use. var f *field fields := cachedTypeFields(t.Type()) for i := range fields { ff := &fields[i] if bytes.Equal(ff.nameBytes, keyBytes) { f = ff break } // Do case-insensitive comparison. if f == nil && ff.equalFold(ff.nameBytes, keyBytes) { f = ff } } if f != nil { // Find the reflect.Value of the most preferential // struct field. jtf := t.Field(f.index[0]) typedYAMLObj[k], err = convertToJSONableObject(v, &jtf) if err != nil { return nil, err } continue } } else if t.Kind() == reflect.Map { // Create a zero value of the map's element type to use as // the JSON target. jtv := reflect.Zero(t.Type().Elem()) typedYAMLObj[k], err = convertToJSONableObject(v, &jtv) if err != nil { return nil, err } continue } } typedYAMLObj[k], err = convertToJSONableObject(v, nil) if err != nil { return nil, err } } return typedYAMLObj, nil case []interface{}: // We need to recurse into arrays in case there are any // map[interface{}]interface{}'s inside and to convert any // numbers to strings. // If jsonTarget is a slice (which it really should be), find the // thing it's going to map to. If it's not a slice, just pass nil // - JSON conversion will error for us if it's a real issue. var jsonSliceElemValue *reflect.Value if jsonTarget != nil { t := *jsonTarget if t.Kind() == reflect.Slice { // By default slices point to nil, but we need a reflect.Value // pointing to a value of the slice type, so we create one here. ev := reflect.Indirect(reflect.New(t.Type().Elem())) jsonSliceElemValue = &ev } } // Make and use a new array. arr := make([]interface{}, len(typedYAMLObj)) for i, v := range typedYAMLObj { arr[i], err = convertToJSONableObject(v, jsonSliceElemValue) if err != nil { return nil, err } } return arr, nil default: // If the target type is a string and the YAML type is a number, // convert the YAML type to a string. if jsonTarget != nil && (*jsonTarget).Kind() == reflect.String { // Based on my reading of go-yaml, it may return int, int64, // float64, or uint64. var s string switch typedVal := typedYAMLObj.(type) { case int: s = strconv.FormatInt(int64(typedVal), 10) case int64: s = strconv.FormatInt(typedVal, 10) case float64: s = strconv.FormatFloat(typedVal, 'g', -1, 64) case uint64: s = strconv.FormatUint(typedVal, 10) case bool: if typedVal { s = "true" } else { s = "false" } } if len(s) > 0 { yamlObj = interface{}(s) } } return yamlObj, nil } } yaml-0.2.0/yaml_test.go000066400000000000000000000210321424774604100150120ustar00rootroot00000000000000package yaml import ( "fmt" "math" "reflect" "runtime" "strconv" "strings" "testing" ) type MarshalTest struct { A string B int64 C float32 D float64 } func TestMarshal(t *testing.T) { f32String := strconv.FormatFloat(math.MaxFloat32, 'g', -1, 32) f64String := strconv.FormatFloat(math.MaxFloat64, 'g', -1, 64) s := MarshalTest{"a", math.MaxInt64, math.MaxFloat32, math.MaxFloat64} e := []byte(fmt.Sprintf("A: a\nB: %d\nC: %s\nD: %s\n", int64(math.MaxInt64), f32String, f64String)) y, err := Marshal(s) if err != nil { t.Errorf("error marshaling YAML: %v", err) } if !reflect.DeepEqual(y, e) { t.Errorf("marshal YAML was unsuccessful, expected: %#v, got: %#v", string(e), string(y)) } } type UnmarshalString struct { A string B string } type UnmarshalStringMap struct { A map[string]string } type UnmarshalNestedString struct { A NestedString } type NestedString struct { A string } type UnmarshalSlice struct { A []NestedSlice } type NestedSlice struct { B string C *string } func TestUnmarshal(t *testing.T) { y := []byte(``) s1 := UnmarshalString{} e1 := UnmarshalString{} unmarshalEqual(t, y, &s1, &e1) y = []byte(`{}`) s1 = UnmarshalString{} e1 = UnmarshalString{} unmarshalEqual(t, y, &s1, &e1) y = []byte("a: 1") s1 = UnmarshalString{} e1 = UnmarshalString{A: "1"} unmarshalEqual(t, y, &s1, &e1) y = []byte(`a: "1"`) s1 = UnmarshalString{} e1 = UnmarshalString{A: "1"} unmarshalEqual(t, y, &s1, &e1) y = []byte("a: true") s1 = UnmarshalString{} e1 = UnmarshalString{A: "true"} unmarshalEqual(t, y, &s1, &e1) y = []byte("a: 1") s1 = UnmarshalString{} e1 = UnmarshalString{A: "1"} unmarshalEqual(t, y, &s1, &e1) y = []byte("a:\n a: 1") s2 := UnmarshalNestedString{} e2 := UnmarshalNestedString{NestedString{"1"}} unmarshalEqual(t, y, &s2, &e2) y = []byte("a:\n - b: abc\n c: def\n - b: 123\n c: 456\n") s3 := UnmarshalSlice{} e3 := UnmarshalSlice{[]NestedSlice{{"abc", strPtr("def")}, {"123", strPtr("456")}}} unmarshalEqual(t, y, &s3, &e3) y = []byte("a:\n b: 1") s4 := UnmarshalStringMap{} e4 := UnmarshalStringMap{map[string]string{"b": "1"}} unmarshalEqual(t, y, &s4, &e4) y = []byte(` a: name: TestA b: name: TestB `) type NamedThing struct { Name string `json:"name"` } s5 := map[string]*NamedThing{} e5 := map[string]*NamedThing{ "a": {Name: "TestA"}, "b": {Name: "TestB"}, } unmarshalEqual(t, y, &s5, &e5) } // TestUnmarshalNonStrict tests that we parse ambiguous YAML without error. func TestUnmarshalNonStrict(t *testing.T) { for _, tc := range []struct { yaml []byte want UnmarshalString }{ { yaml: []byte("a: 1"), want: UnmarshalString{A: "1"}, }, { // Order does not matter. yaml: []byte("b: 1\na: 2"), want: UnmarshalString{A: "2", B: "1"}, }, { // Unknown field get ignored. yaml: []byte("a: 1\nunknownField: 2"), want: UnmarshalString{A: "1"}, }, { // Unknown fields get ignored. yaml: []byte("unknownOne: 2\na: 1\nunknownTwo: 2"), want: UnmarshalString{A: "1"}, }, { // In YAML, `YES` is no longer Boolean true. yaml: []byte("a: YES"), want: UnmarshalString{A: "YES"}, }, } { s := UnmarshalString{} unmarshalEqual(t, tc.yaml, &s, &tc.want) } } // prettyFunctionName converts a slice of JSONOpt function pointers to a human // readable string representation. func prettyFunctionName(opts []JSONOpt) []string { var r []string for _, o := range opts { r = append(r, runtime.FuncForPC(reflect.ValueOf(o).Pointer()).Name()) } return r } func unmarshalEqual(t *testing.T, y []byte, s, e interface{}, opts ...JSONOpt) { //nolint:unparam t.Helper() err := Unmarshal(y, s, opts...) if err != nil { t.Errorf("Unmarshal(%#q, s, %v) = %v", string(y), prettyFunctionName(opts), err) return } if !reflect.DeepEqual(s, e) { t.Errorf("Unmarshal(%#q, s, %v) = %+#v; want %+#v", string(y), prettyFunctionName(opts), s, e) } } // TestUnmarshalErrors tests that we return an error on ambiguous YAML. func TestUnmarshalErrors(t *testing.T) { for _, tc := range []struct { yaml []byte wantErr string }{ { // Declaring `a` twice produces an error. yaml: []byte("a: 1\na: 2"), wantErr: `key "a" already defined`, }, { // Not ignoring first declaration of A with wrong type. yaml: []byte("a: [1,2,3]\na: value-of-a"), wantErr: `key "a" already defined`, }, { // Declaring field `true` twice. yaml: []byte("true: string-value-of-yes\ntrue: 1"), wantErr: `key "true" already defined`, }, } { s := UnmarshalString{} err := Unmarshal(tc.yaml, &s) if tc.wantErr != "" && err == nil { t.Errorf("Unmarshal(%#q, &s) = nil; want error", string(tc.yaml)) continue } if tc.wantErr == "" && err != nil { t.Errorf("Unmarshal(%#q, &s) = %v; want no error", string(tc.yaml), err) continue } // We only expect errors during unmarshalling YAML. if tc.wantErr != "" && !strings.Contains(err.Error(), tc.wantErr) { t.Errorf("Unmarshal(%#q, &s) = %v; want err contains %#q", string(tc.yaml), err, tc.wantErr) } } } type Case struct { input string output string // By default we test that reversing the output == input. But if there is a // difference in the reversed output, you can optionally specify it here. reverse *string } type RunType int const ( RunTypeJSONToYAML RunType = iota RunTypeYAMLToJSON ) func TestJSONToYAML(t *testing.T) { cases := []Case{ { `{"t":"a"}`, "t: a\n", nil, }, { `{"t":null}`, "t: null\n", nil, }, } runCases(t, RunTypeJSONToYAML, cases) } func TestYAMLToJSON(t *testing.T) { cases := []Case{ { "t: a\n", `{"t":"a"}`, nil, }, { "t: \n", `{"t":null}`, strPtr("t: null\n"), }, { "t: null\n", `{"t":null}`, nil, }, { "true: yes\n", `{"true":"yes"}`, strPtr("\"true\": \"yes\"\n"), }, { "false: yes\n", `{"false":"yes"}`, strPtr("\"false\": \"yes\"\n"), }, { "1: a\n", `{"1":"a"}`, strPtr("\"1\": a\n"), }, { "1000000000000000000000000000000000000: a\n", `{"1e+36":"a"}`, strPtr("\"1e+36\": a\n"), }, { "1e+36: a\n", `{"1e+36":"a"}`, strPtr("\"1e+36\": a\n"), }, { "\"1e+36\": a\n", `{"1e+36":"a"}`, nil, }, { "\"1.2\": a\n", `{"1.2":"a"}`, nil, }, { "- t: a\n", `[{"t":"a"}]`, nil, }, { "- t: a\n" + "- t:\n" + " b: 1\n" + " c: 2\n", `[{"t":"a"},{"t":{"b":1,"c":2}}]`, nil, }, { `[{t: a}, {t: {b: 1, c: 2}}]`, `[{"t":"a"},{"t":{"b":1,"c":2}}]`, strPtr("- t: a\n" + "- t:\n" + " b: 1\n" + " c: 2\n"), }, { "- t: \n", `[{"t":null}]`, strPtr("- t: null\n"), }, { "- t: null\n", `[{"t":null}]`, nil, }, } // Cases that should produce errors. _ = []Case{ { "~: a", `{"null":"a"}`, nil, }, { "a: !!binary gIGC\n", "{\"a\":\"\x80\x81\x82\"}", nil, }, } runCases(t, RunTypeYAMLToJSON, cases) } func runCases(t *testing.T, runType RunType, cases []Case) { var f func([]byte) ([]byte, error) var invF func([]byte) ([]byte, error) var msg string var invMsg string if runType == RunTypeJSONToYAML { f = JSONToYAML invF = YAMLToJSON msg = "JSON to YAML" invMsg = "YAML back to JSON" } else { f = YAMLToJSON invF = JSONToYAML msg = "YAML to JSON" invMsg = "JSON back to YAML" } for _, c := range cases { // Convert the string. t.Logf("converting %s\n", c.input) output, err := f([]byte(c.input)) if err != nil { t.Errorf("Failed to convert %s, input: `%s`, err: %v", msg, c.input, err) } // Check it against the expected output. if string(output) != c.output { t.Errorf("Failed to convert %s, input: `%s`, expected `%s`, got `%s`", msg, c.input, c.output, string(output)) } // Set the string that we will compare the reversed output to. reverse := c.input // If a special reverse string was specified, use that instead. if c.reverse != nil { reverse = *c.reverse } // Reverse the output. input, err := invF(output) if err != nil { t.Errorf("Failed to convert %s, input: `%s`, err: %v", invMsg, string(output), err) } // Check the reverse is equal to the input (or to *c.reverse). if string(input) != reverse { t.Errorf("Failed to convert %s, input: `%s`, expected `%s`, got `%s`", invMsg, string(output), reverse, string(input)) } } } // To be able to easily fill in the *Case.reverse string above. func strPtr(s string) *string { return &s } func TestYAMLToJSONDuplicateFields(t *testing.T) { data := []byte("foo: bar\nfoo: baz\n") if _, err := YAMLToJSON(data); err == nil { t.Error("expected YAMLtoJSON to fail on duplicate field names") } }