├── .github └── workflows │ └── go.yml ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── build.sh ├── convert ├── encoding.go ├── hcl.go ├── json.go ├── toml.go └── yaml.go ├── flags.go ├── flags_test.go ├── go.mod ├── go.sum ├── hcl └── decoder.go ├── logo.png ├── main.go ├── main_test.go ├── order └── map.go ├── testdata ├── case1_in.json ├── case1_out_jc.hcl ├── case1_out_jjie.json ├── case1_out_jt.toml ├── case1_out_jy.yml ├── case1_out_jyk.yml ├── case1_out_jyn.yml ├── case2_in.yml ├── case2_out_yc.hcl ├── case2_out_yji.json ├── case2_out_yjie.json ├── case2_out_yjin.json ├── case2_out_yt.toml ├── case3_in.toml ├── case3_out_tc.hcl ├── case3_out_tji.json ├── case3_out_tjie.json ├── case3_out_ty.yml ├── case3_out_tyk.yml ├── case4_in.hcl ├── case4_out_cji.json ├── case4_out_ct.hcl ├── case4_out_cy.yml ├── case4_out_cyk.yml └── case4_out_cyn.yml ├── toml ├── decoder.go ├── encoder.go └── util.go └── yaml ├── decoder.go ├── encoder.go ├── json.go └── util.go /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | name: Go 2 | on: 3 | push: 4 | branches: [ main ] 5 | pull_request: 6 | branches: [ main ] 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v2 12 | - name: Set up Go 13 | uses: actions/setup-go@v2 14 | with: 15 | go-version: 1.18 16 | - name: Fmt 17 | run: test -z $(go fmt ./...) 18 | - name: Vet 19 | run: go vet ./... 20 | - name: Build 21 | run: go build -v ./... 22 | - name: Test 23 | run: go test -v ./... 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .idea 3 | *.coverprofile 4 | *~ 5 | 6 | /build-v* 7 | /yj 8 | 9 | # Binaries for programs and plugins 10 | *.exe 11 | *.exe~ 12 | *.dll 13 | *.so 14 | *.dylib 15 | 16 | # Test binary, built with `go test -c` 17 | *.test 18 | 19 | # Output of the go coverage tool, specifically when used with LiteIDE 20 | *.out 21 | 22 | # Dependency directories (remove the comment below to include it) 23 | # vendor/ -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:alpine AS builder 2 | RUN apk update && apk add --no-cache git 3 | WORKDIR /workspace 4 | COPY . . 5 | ARG version="0.0.0" 6 | RUN go build -ldflags "-X main.Version=$version" . 7 | FROM scratch 8 | COPY --from=builder /workspace/yj /bin/yj 9 | ENTRYPOINT ["/bin/yj"] 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2018 Stephen C. Levine 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | yj 2 | 3 | [![GoDoc](https://pkg.go.dev/badge/github.com/sclevine/yj/v5?status.svg)](https://pkg.go.dev/github.com/sclevine/yj/v5) 4 | [![Tests](https://github.com/sclevine/yj/actions/workflows/go.yml/badge.svg)](https://github.com/sclevine/yj/actions/workflows/go.yml) 5 | 6 | [![Packaging status](https://repology.org/badge/tiny-repos/yj-sclevine.svg)](https://repology.org/project/yj-sclevine/versions) 7 | 8 | ## 9 | 10 | Convert between YAML, TOML, JSON, and HCL. 11 | 12 | Preserves map order. 13 | 14 | Format versions: 15 | - YAML: **v1.2** (gopkg.in/yaml.v3) 16 | - TOML: **v1.0.0** (github.com/BurntSushi/toml) 17 | - JSON: **RFC 7159** (encoding/json) 18 | - HCL: **v1** (github.com/hashicorp/hcl) 19 | 20 | ``` 21 | $ yj -h 22 | Usage: yj [-][ytjcrneikhv] 23 | 24 | Convert between YAML, TOML, JSON, and HCL. 25 | Preserves map order. 26 | 27 | -x[x] Convert using stdin. Valid options: 28 | -yj, -y = YAML to JSON (default) 29 | -yy = YAML to YAML 30 | -yt = YAML to TOML 31 | -yc = YAML to HCL 32 | -tj, -t = TOML to JSON 33 | -ty = TOML to YAML 34 | -tt = TOML to TOML 35 | -tc = TOML to HCL 36 | -jj = JSON to JSON 37 | -jy, -r = JSON to YAML 38 | -jt = JSON to TOML 39 | -jc = JSON to HCL 40 | -cy = HCL to YAML 41 | -ct = HCL to TOML 42 | -cj, -c = HCL to JSON 43 | -cc = HCL to HCL 44 | -n Do not covert inf, -inf, and NaN to/from strings (YAML or TOML only) 45 | -e Escape HTML (JSON out only) 46 | -i Indent output (JSON or TOML out only) 47 | -k Attempt to parse keys as objects or numeric types (YAML out only) 48 | -h Show this help message 49 | -v Show version 50 | ``` 51 | 52 | ## Installation 53 | 54 | ### Homebrew 55 | 56 | The `yj` CLI is available via [Homebrew](https://brew.sh): 57 | 58 | ```bash 59 | brew install yj 60 | ``` 61 | 62 | ### Manual 63 | 64 | Binaries for macOS, Linux, and Windows are [attached to each release](https://github.com/sclevine/yj/releases). 65 | 66 | ### Docker 67 | 68 | `yj` is also available as a [Docker image](https://hub.docker.com/r/sclevine/yj). 69 | 70 | ## Go Package 71 | 72 | Packages contained in this repo may also be used to convert all supported data formats to a normalized tree of ordered Go objects. 73 | 74 | See [godoc](https://pkg.go.dev/github.com/sclevine/yj) for details. 75 | 76 | NOTE: The current Go API should not be considered stable. 77 | -------------------------------------------------------------------------------- /build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | 5 | version=${1:-0.0.0} 6 | out=build-v${version} 7 | cd "$(dirname "${BASH_SOURCE[0]}")" 8 | mkdir -p "$out" 9 | 10 | GOOS=darwin GOARCH=amd64 go build -ldflags "-X main.Version=$version" -o "$out/yj-macos-amd64" . 11 | GOOS=darwin GOARCH=arm64 go build -ldflags "-X main.Version=$version" -o "$out/yj-macos-arm64" . 12 | GOOS=linux GOARCH=amd64 go build -ldflags "-X main.Version=$version" -o "$out/yj-linux-amd64" . 13 | GOOS=linux GOARCH=arm64 go build -ldflags "-X main.Version=$version" -o "$out/yj-linux-arm64" . 14 | GOOS=linux GOARCH=arm GOARM=5 go build -ldflags "-X main.Version=$version" -o "$out/yj-linux-arm-v5" . 15 | GOOS=linux GOARCH=arm GOARM=7 go build -ldflags "-X main.Version=$version" -o "$out/yj-linux-arm-v7" . 16 | GOOS=windows GOARCH=amd64 go build -ldflags "-X main.Version=$version" -o "$out/yj.exe" . 17 | 18 | docker build . --build-arg "version=$version" -t "sclevine/yj:$version" 19 | docker tag "sclevine/yj:$version" "sclevine/yj:latest" -------------------------------------------------------------------------------- /convert/encoding.go: -------------------------------------------------------------------------------- 1 | package convert 2 | 3 | import ( 4 | "io" 5 | "math" 6 | ) 7 | 8 | type Encoding interface { 9 | String() string 10 | Encode(w io.Writer, in interface{}) error 11 | Decode(r io.Reader) (interface{}, error) 12 | } 13 | 14 | type SpecialFloats int 15 | 16 | const ( 17 | FloatsReal SpecialFloats = iota 18 | FloatsString 19 | FloatsNumber 20 | ) 21 | 22 | func (s SpecialFloats) NaN() interface{} { 23 | switch s { 24 | case FloatsReal: 25 | return math.NaN() 26 | case FloatsString: 27 | return "NaN" 28 | case FloatsNumber: 29 | return (*float64)(nil) 30 | } 31 | panic("NaN: invalid special float type") 32 | } 33 | 34 | func (s SpecialFloats) PosInf() interface{} { 35 | switch s { 36 | case FloatsReal: 37 | return math.Inf(1) 38 | case FloatsString: 39 | return "Infinity" 40 | case FloatsNumber: 41 | return math.MaxFloat64 42 | } 43 | panic("PosInf: invalid special float type") 44 | } 45 | 46 | func (s SpecialFloats) NegInf() interface{} { 47 | switch s { 48 | case FloatsReal: 49 | return math.Inf(-1) 50 | case FloatsString: 51 | return "-Infinity" 52 | case FloatsNumber: 53 | return -math.MaxFloat64 54 | } 55 | panic("NegInf: invalid special float type") 56 | } 57 | -------------------------------------------------------------------------------- /convert/hcl.go: -------------------------------------------------------------------------------- 1 | package convert 2 | 3 | import ( 4 | "bytes" 5 | "io" 6 | "io/ioutil" 7 | 8 | gohcl "github.com/hashicorp/hcl" 9 | "github.com/hashicorp/hcl/hcl/printer" 10 | hcljson "github.com/hashicorp/hcl/json/parser" 11 | 12 | "github.com/sclevine/yj/v5/hcl" 13 | ) 14 | 15 | type HCL struct{} 16 | 17 | func (HCL) String() string { 18 | return "HCL" 19 | } 20 | 21 | func (HCL) Encode(w io.Writer, in interface{}) error { 22 | j := &bytes.Buffer{} 23 | if err := (JSON{}).Encode(j, in); err != nil { 24 | return err 25 | } 26 | f, err := hcljson.Parse(j.Bytes()) 27 | if err != nil { 28 | return err 29 | } 30 | return printer.Fprint(w, f) 31 | } 32 | 33 | func (HCL) Decode(r io.Reader) (interface{}, error) { 34 | in, err := ioutil.ReadAll(r) 35 | if err != nil { 36 | return nil, err 37 | } 38 | f, err := gohcl.ParseBytes(in) 39 | if err != nil { 40 | return nil, err 41 | } 42 | dec := hcl.Decoder{} 43 | return dec.Decode(f.Node) 44 | } 45 | -------------------------------------------------------------------------------- /convert/json.go: -------------------------------------------------------------------------------- 1 | package convert 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "errors" 7 | "io" 8 | "io/ioutil" 9 | 10 | "github.com/sclevine/yj/v5/order" 11 | ) 12 | 13 | type JSON struct { 14 | EscapeHTML bool 15 | Indent bool 16 | } 17 | 18 | func (JSON) String() string { 19 | return "JSON" 20 | } 21 | 22 | func (j JSON) Encode(w io.Writer, in interface{}) error { 23 | encoder := json.NewEncoder(w) 24 | encoder.SetEscapeHTML(j.EscapeHTML) 25 | // TODO: remove global, may affect yaml/json.go 26 | defer func(p bool) { 27 | order.MapSliceEscapeHTML = p 28 | }(order.MapSliceEscapeHTML) 29 | order.MapSliceEscapeHTML = j.EscapeHTML 30 | if j.Indent { 31 | encoder.SetIndent("", " ") 32 | } 33 | return encoder.Encode(in) 34 | } 35 | 36 | // TODO: implement streaming version 37 | func (JSON) Decode(r io.Reader) (interface{}, error) { 38 | out, err := ioutil.ReadAll(r) 39 | if err != nil { 40 | return nil, err 41 | } 42 | if !json.Valid(out) { 43 | var null interface{} 44 | err := json.Unmarshal(out, &null) 45 | if err == nil { 46 | err = errors.New("invalid JSON") 47 | } 48 | return nil, err 49 | } 50 | return (YAML{}).Decode(bytes.NewReader(out)) 51 | } 52 | -------------------------------------------------------------------------------- /convert/toml.go: -------------------------------------------------------------------------------- 1 | package convert 2 | 3 | import ( 4 | "io" 5 | 6 | gotoml "github.com/BurntSushi/toml" 7 | 8 | "github.com/sclevine/yj/v5/toml" 9 | ) 10 | 11 | type TOML struct { 12 | SpecialFloats 13 | Indent bool 14 | } 15 | 16 | func (TOML) String() string { 17 | return "TOML" 18 | } 19 | 20 | func (t TOML) Encode(w io.Writer, in interface{}) error { 21 | tomlEnc := gotoml.NewEncoder(w) 22 | if !t.Indent { 23 | tomlEnc.Indent = "" 24 | } 25 | enc := toml.Encoder{ 26 | NaN: t.NaN(), 27 | PosInf: t.PosInf(), 28 | NegInf: t.NegInf(), 29 | } 30 | out, err := enc.Encode(in) 31 | if err != nil { 32 | return err 33 | } 34 | return tomlEnc.Encode(out) 35 | } 36 | 37 | func (t TOML) Decode(r io.Reader) (interface{}, error) { 38 | var out interface{} 39 | md, err := gotoml.NewDecoder(r).Decode(&out) 40 | if err != nil { 41 | return nil, err 42 | } 43 | dec := toml.Decoder{ 44 | NaN: t.NaN(), 45 | PosInf: t.PosInf(), 46 | NegInf: t.NegInf(), 47 | } 48 | return dec.Decode(out, md.Keys()) 49 | } 50 | -------------------------------------------------------------------------------- /convert/yaml.go: -------------------------------------------------------------------------------- 1 | package convert 2 | 3 | import ( 4 | "io" 5 | 6 | goyaml "gopkg.in/yaml.v3" 7 | 8 | "github.com/sclevine/yj/v5/yaml" 9 | ) 10 | 11 | type YAML struct { 12 | SpecialFloats 13 | KeySpecialFloats SpecialFloats 14 | JSONKeys bool 15 | EscapeHTML bool 16 | } 17 | 18 | func (YAML) String() string { 19 | return "YAML" 20 | } 21 | 22 | func (y YAML) Encode(w io.Writer, in interface{}) error { 23 | enc := &yaml.Encoder{ 24 | NaN: y.NaN(), 25 | PosInf: y.PosInf(), 26 | NegInf: y.NegInf(), 27 | KeyNaN: y.KeySpecialFloats.NaN(), 28 | KeyPosInf: y.KeySpecialFloats.PosInf(), 29 | KeyNegInf: y.KeySpecialFloats.NegInf(), 30 | } 31 | if y.JSONKeys { 32 | enc.KeyUnmarshal = (&yaml.KeyJSON{}).Unmarshal 33 | } 34 | out, err := enc.Encode(in) 35 | if err != nil { 36 | return err 37 | } 38 | yamlEnc := goyaml.NewEncoder(w) 39 | yamlEnc.SetIndent(2) 40 | return yamlEnc.Encode(out) 41 | } 42 | 43 | func (y YAML) Decode(r io.Reader) (interface{}, error) { 44 | var node goyaml.Node 45 | if err := goyaml.NewDecoder(r).Decode(&node); err != nil { 46 | return nil, err 47 | } 48 | dec := &yaml.Decoder{ 49 | KeyMarshal: (&yaml.KeyJSON{EscapeHTML: y.EscapeHTML}).Marshal, // FIXME: double-check map-keys 50 | NaN: y.NaN(), 51 | PosInf: y.PosInf(), 52 | NegInf: y.NegInf(), 53 | KeyNaN: y.KeySpecialFloats.NaN(), 54 | KeyPosInf: y.KeySpecialFloats.PosInf(), 55 | KeyNegInf: y.KeySpecialFloats.NegInf(), 56 | } 57 | return dec.Decode(&node) 58 | } 59 | -------------------------------------------------------------------------------- /flags.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | 7 | "github.com/sclevine/yj/v5/convert" 8 | ) 9 | 10 | type Config struct { 11 | From, To convert.Encoding 12 | Help, Version bool 13 | } 14 | 15 | const ( 16 | FlagYAML = 'y' 17 | FlagTOML = 't' 18 | FlagJSON = 'j' 19 | FlagHCL = 'c' 20 | FlagReverse = 'r' 21 | FlagNoFloatStrings = 'n' 22 | FlagEscapeHTML = 'e' 23 | FlagIndent = 'i' 24 | FlagJSONKeys = 'k' 25 | FlagHelp = 'h' 26 | FlagVersion = 'v' 27 | ) 28 | 29 | func Parse(args ...string) (*Config, error) { 30 | flatArgs := strings.Join(args, "") 31 | invalidArgs := strings.Split(strings.Map(flagFilter, flatArgs), "") 32 | 33 | if len(invalidArgs) > 0 { 34 | return nil, fmt.Errorf("invalid flags specified: %s", strings.Join(invalidArgs, " ")) 35 | } 36 | 37 | from, to, err := transform(flatArgs) 38 | if err != nil { 39 | return nil, err 40 | } 41 | config := &Config{ 42 | From: from, 43 | To: to, 44 | Help: strings.ContainsRune(flatArgs, FlagHelp), 45 | Version: strings.ContainsRune(flatArgs, FlagVersion), 46 | } 47 | 48 | return config, nil 49 | } 50 | 51 | func flagFilter(r rune) rune { 52 | switch r { 53 | case FlagYAML, FlagTOML, FlagJSON, FlagHCL, FlagReverse, 54 | FlagEscapeHTML, FlagNoFloatStrings, FlagJSONKeys, 55 | FlagIndent, FlagHelp, FlagVersion, '\t', ' ', '-': 56 | return -1 57 | } 58 | return r 59 | } 60 | 61 | func transform(s string) (from, to convert.Encoding, err error) { 62 | escapeHTML := strings.ContainsRune(s, FlagEscapeHTML) 63 | indent := strings.ContainsRune(s, FlagIndent) 64 | jsonKeys := strings.ContainsRune(s, FlagJSONKeys) 65 | floatStrings := !strings.ContainsRune(s, FlagNoFloatStrings) 66 | 67 | yaml := &convert.YAML{ 68 | JSONKeys: jsonKeys, 69 | EscapeHTML: escapeHTML, 70 | } 71 | toml := &convert.TOML{ 72 | Indent: indent, 73 | } 74 | json := &convert.JSON{ 75 | EscapeHTML: escapeHTML, 76 | Indent: indent, 77 | } 78 | hcl := &convert.HCL{} 79 | 80 | for _, r := range s { 81 | switch r { 82 | case FlagYAML: 83 | from, to = to, yaml 84 | case FlagTOML: 85 | from, to = to, toml 86 | case FlagJSON: 87 | from, to = to, json 88 | case FlagHCL: 89 | from, to = to, hcl 90 | case FlagReverse: 91 | from, to = json, yaml 92 | } 93 | } 94 | if from == nil { 95 | if to == nil { 96 | to = yaml 97 | } 98 | from, to = to, json 99 | } 100 | 101 | setKeyFloats(to, func(setTo func(v convert.SpecialFloats)) { 102 | if floatStrings { 103 | setTo(convert.FloatsString) 104 | } else { 105 | // never convert number to nan, inf, -inf 106 | setTo(convert.FloatsReal) 107 | } 108 | }) 109 | 110 | setKeyFloats(from, func(setFrom func(v convert.SpecialFloats)) { 111 | if floatStrings { 112 | setFrom(convert.FloatsString) 113 | } else { 114 | setFrom(convert.FloatsNumber) 115 | } 116 | }) 117 | 118 | setFloats(to, func(setTo func(v convert.SpecialFloats)) { 119 | if floatStrings { 120 | setTo(convert.FloatsString) 121 | } else { 122 | // never convert number to nan, inf, -inf 123 | setTo(convert.FloatsReal) 124 | } 125 | }) 126 | 127 | setFloats(from, func(setFrom func(v convert.SpecialFloats)) { 128 | if floatStrings { 129 | setFrom(convert.FloatsString) 130 | } else { 131 | setFrom(convert.FloatsNumber) 132 | } 133 | setFloats(to, func(setTo func(v convert.SpecialFloats)) { 134 | setFrom(convert.FloatsReal) 135 | setTo(convert.FloatsReal) 136 | }) 137 | }) 138 | 139 | if _, toYAML := to.(*convert.YAML); jsonKeys && !toYAML { 140 | err = fmt.Errorf("flag -%c only valid for YAML output", FlagJSONKeys) 141 | return 142 | } 143 | if _, toJSON := to.(*convert.JSON); escapeHTML && !toJSON { 144 | err = fmt.Errorf("flag -%c only valid for JSON output", FlagEscapeHTML) 145 | return 146 | } 147 | 148 | if indent { 149 | switch to.(type) { 150 | case *convert.JSON, *convert.TOML: 151 | default: 152 | err = fmt.Errorf("flag -%c only valid for JSON or TOML output", FlagIndent) 153 | return 154 | } 155 | } 156 | 157 | // TODO: validate -n isn't used between inapplicable types 158 | 159 | return 160 | } 161 | 162 | func setFloats(e convert.Encoding, f func(set func(v convert.SpecialFloats))) { 163 | switch e := e.(type) { 164 | case *convert.YAML: 165 | f(func(v convert.SpecialFloats) { e.SpecialFloats = v }) 166 | case *convert.TOML: 167 | f(func(v convert.SpecialFloats) { e.SpecialFloats = v }) 168 | } 169 | } 170 | 171 | func setKeyFloats(e convert.Encoding, f func(set func(v convert.SpecialFloats))) { 172 | switch e := e.(type) { 173 | case *convert.YAML: 174 | f(func(v convert.SpecialFloats) { e.KeySpecialFloats = v }) 175 | } 176 | } 177 | -------------------------------------------------------------------------------- /flags_test.go: -------------------------------------------------------------------------------- 1 | package main_test 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/sclevine/yj/v5" 7 | "github.com/sclevine/yj/v5/convert" 8 | ) 9 | 10 | func TestParse(t *testing.T) { 11 | config, err := main.Parse("-t", "y\tk-", "kn-k ", "h h", "") 12 | assertEq(t, err, nil) 13 | toml, ok := config.From.(*convert.TOML) 14 | assertEq(t, ok, true) 15 | assertEq(t, toml, &convert.TOML{ 16 | SpecialFloats: convert.FloatsReal, 17 | }) 18 | yaml, ok := config.To.(*convert.YAML) 19 | assertEq(t, ok, true) 20 | assertEq(t, yaml, &convert.YAML{ 21 | SpecialFloats: convert.FloatsReal, 22 | EscapeHTML: false, 23 | JSONKeys: true, 24 | }) 25 | assertEq(t, config.Help, true) 26 | 27 | config, err = main.Parse("--\t\te ", "") 28 | assertEq(t, err, nil) 29 | yaml, ok = config.From.(*convert.YAML) 30 | assertEq(t, ok, true) 31 | assertEq(t, yaml, &convert.YAML{ 32 | SpecialFloats: convert.FloatsString, 33 | KeySpecialFloats: convert.FloatsString, 34 | EscapeHTML: true, 35 | JSONKeys: false, 36 | }) 37 | json, ok := config.To.(*convert.JSON) 38 | assertEq(t, ok, true) 39 | assertEq(t, json, &convert.JSON{ 40 | EscapeHTML: true, 41 | }) 42 | assertEq(t, config.Help, false) 43 | 44 | // TODO: test more ytjc combinations 45 | } 46 | 47 | func TestParseWithInvalidFlags(t *testing.T) { 48 | _, err := main.Parse("-ar", "yb\te-", "kn-k ", "h ~ dh", "ab") 49 | assertEq(t, err.Error(), "invalid flags specified: a b ~ d a b") 50 | 51 | _, err = main.Parse("k") 52 | assertEq(t, err.Error(), "flag -k only valid for YAML output") 53 | 54 | _, err = main.Parse("ejy") 55 | assertEq(t, err.Error(), "flag -e only valid for JSON output") 56 | 57 | _, err = main.Parse("ijy") 58 | assertEq(t, err.Error(), "flag -i only valid for JSON or TOML output") 59 | } 60 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/sclevine/yj/v5 2 | 3 | go 1.21 4 | 5 | require ( 6 | github.com/BurntSushi/toml v1.3.2 7 | github.com/hashicorp/hcl v1.0.0 8 | gopkg.in/yaml.v3 v3.0.1 9 | ) 10 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/BurntSushi/toml v1.3.2 h1:o7IhLm0Msx3BaB+n3Ag7L8EVlByGnpq14C4YWiu/gL8= 2 | github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= 3 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 4 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 5 | github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= 6 | github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= 7 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 8 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 9 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 10 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 11 | -------------------------------------------------------------------------------- /hcl/decoder.go: -------------------------------------------------------------------------------- 1 | package hcl 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/hashicorp/hcl" 7 | "github.com/hashicorp/hcl/hcl/ast" 8 | 9 | "github.com/sclevine/yj/v5/order" 10 | ) 11 | 12 | type Decoder struct{} 13 | 14 | func (d *Decoder) Decode(node ast.Node) (out interface{}, err error) { 15 | defer catchFailure(&err) 16 | return d.normalize(node), nil 17 | } 18 | 19 | func (d *Decoder) normalize(node ast.Node) interface{} { 20 | switch n := node.(type) { 21 | case *ast.ObjectList: 22 | done := make(map[string]struct{}) 23 | list := newObjList() 24 | for _, item := range n.Items { 25 | if item.Val == nil { 26 | continue 27 | } 28 | if len(item.Keys) == 0 { 29 | panic(fmt.Errorf("empty key at line %d", item.Pos().Line)) 30 | } 31 | key := item.Keys[0].Token.Value().(string) 32 | if _, ok := done[key]; ok { 33 | continue 34 | } 35 | itemVal := item.Val 36 | if len(item.Keys) > 1 { 37 | itemVal = n.Filter(key) 38 | done[key] = struct{}{} 39 | } 40 | val := d.normalize(itemVal) 41 | switch val := val.(type) { 42 | case []interface{}: 43 | for _, v := range val { 44 | list.append(key, v) 45 | } 46 | case order.MapSlice: 47 | list.append(key, val) 48 | default: 49 | list.set(key, val) 50 | } 51 | } 52 | return list.mapSlice() 53 | case *ast.ObjectType: 54 | return d.normalize(n.List) 55 | case *ast.ListType: 56 | out := make([]interface{}, 0, len(n.List)) 57 | for _, item := range n.List { 58 | out = append(out, d.normalize(item)) 59 | } 60 | return out 61 | case *ast.LiteralType: 62 | var out interface{} 63 | if err := hcl.DecodeObject(&out, n); err != nil { 64 | panic(err) 65 | } 66 | return out 67 | default: 68 | panic(fmt.Errorf("invalid type: %#v", n)) 69 | } 70 | } 71 | 72 | type objList struct { 73 | keys []string 74 | m map[string]interface{} 75 | } 76 | 77 | func newObjList() *objList { 78 | return &objList{ 79 | m: make(map[string]interface{}), 80 | } 81 | } 82 | 83 | func (l *objList) append(k string, v interface{}) { 84 | if dst, ok := l.m[k]; ok { 85 | dstList, ok := dst.([]interface{}) 86 | if !ok { 87 | panic(fmt.Errorf("cannot append '%#v' to '%#v", v, dst)) 88 | } 89 | l.m[k] = append(dstList, v) 90 | } else { 91 | l.keys = append(l.keys, k) 92 | l.m[k] = []interface{}{v} 93 | } 94 | } 95 | 96 | func (l *objList) set(k string, v interface{}) { 97 | if dst, ok := l.m[k]; ok { 98 | if dstList, ok := dst.([]interface{}); ok { 99 | panic(fmt.Errorf("cannot set '%#v' over '%#v", v, dstList)) 100 | } 101 | } else { 102 | l.keys = append(l.keys, k) 103 | } 104 | l.m[k] = v 105 | } 106 | 107 | func (l *objList) mapSlice() order.MapSlice { 108 | out := make(order.MapSlice, 0, len(l.keys)) 109 | for _, key := range l.keys { 110 | out = append(out, order.MapItem{ 111 | Key: key, 112 | Val: l.m[key], 113 | }) 114 | } 115 | return out 116 | } 117 | 118 | func catchFailure(err *error) { 119 | if r := recover(); r != nil { 120 | var ok bool 121 | if *err, ok = r.(error); !ok { 122 | *err = fmt.Errorf("unexpected failure: %v", r) 123 | } 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sclevine/yj/80164002c0d7f88aa58fa5bec8a8cf4f1bb4e93b/logo.png -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | "os" 7 | ) 8 | 9 | const HelpMsg = `Usage: %s [-][ytjcrneikhv] 10 | 11 | Convert between YAML, TOML, JSON, and HCL. 12 | Preserves map order. 13 | 14 | -x[x] Convert using stdin. Valid options: 15 | -yj, -y = YAML to JSON (default) 16 | -yy = YAML to YAML 17 | -yt = YAML to TOML 18 | -yc = YAML to HCL 19 | -tj, -t = TOML to JSON 20 | -ty = TOML to YAML 21 | -tt = TOML to TOML 22 | -tc = TOML to HCL 23 | -jj = JSON to JSON 24 | -jy, -r = JSON to YAML 25 | -jt = JSON to TOML 26 | -jc = JSON to HCL 27 | -cy = HCL to YAML 28 | -ct = HCL to TOML 29 | -cj, -c = HCL to JSON 30 | -cc = HCL to HCL 31 | -n Do not covert inf, -inf, and NaN to/from strings (YAML or TOML only) 32 | -e Escape HTML (JSON out only) 33 | -i Indent output (JSON or TOML out only) 34 | -k Attempt to parse keys as objects or numeric types (YAML out only) 35 | -h Show this help message 36 | -v Show version 37 | 38 | ` 39 | 40 | var Version = "0.0.0" 41 | 42 | func main() { 43 | os.Exit(Run(os.Stdin, os.Stdout, os.Stderr, os.Args)) 44 | } 45 | 46 | func Run(stdin io.Reader, stdout, stderr io.Writer, osArgs []string) (code int) { 47 | config, err := Parse(osArgs[1:]...) 48 | if err != nil { 49 | fmt.Fprintf(stderr, HelpMsg, os.Args[0]) 50 | fmt.Fprintf(stderr, "Error: %s\n", err) 51 | return 1 52 | } 53 | if config.Help { 54 | fmt.Fprintf(stdout, HelpMsg, os.Args[0]) 55 | return 0 56 | } 57 | if config.Version { 58 | fmt.Fprintln(stdout, "v"+Version) 59 | return 0 60 | } 61 | 62 | rep, err := config.From.Decode(stdin) 63 | if err != nil { 64 | // TODO: I forget if there's a reason this isn't io.EOF 65 | if err.Error() == "EOF" { 66 | return 0 67 | } 68 | fmt.Fprintf(stderr, "Error parsing %s: %s\n", config.From, err) 69 | return 1 70 | } 71 | if err := config.To.Encode(stdout, rep); err != nil { 72 | fmt.Fprintf(stderr, "Error writing %s: %s\n", config.To, err) 73 | return 1 74 | } 75 | return 0 76 | } 77 | -------------------------------------------------------------------------------- /main_test.go: -------------------------------------------------------------------------------- 1 | package main_test 2 | 3 | import ( 4 | "bytes" 5 | "errors" 6 | "io/ioutil" 7 | "path/filepath" 8 | "reflect" 9 | "strings" 10 | "testing" 11 | 12 | main "github.com/sclevine/yj/v5" 13 | ) 14 | 15 | func TestRunWhenArgsFailToParse(t *testing.T) { 16 | stdout, stderr, code := run(nil, "some-bad-args") 17 | assertEq(t, code, 1) 18 | assertEq(t, bytes.Contains(stderr, []byte("Error: invalid flags")), true) 19 | assertEq(t, bytes.Contains(stderr, []byte("Usage:")), true) 20 | assertEq(t, len(stdout), 0) 21 | } 22 | 23 | func TestRunWhenHelpFlagIsProvided(t *testing.T) { 24 | stdout, stderr, code := run(nil, "hr") 25 | assertEq(t, code, 0) 26 | assertEq(t, bytes.Contains(stdout, []byte("Usage:")), true) 27 | assertEq(t, len(stderr), 0) 28 | } 29 | 30 | func TestRunWhenStdinIsInvalid(t *testing.T) { 31 | stdout, stderr := &bytes.Buffer{}, &bytes.Buffer{} 32 | assertEq(t, main.Run(&errReader{}, stdout, stderr, []string{""}), 1) 33 | assertEq(t, strings.Contains(stderr.String(), "some reader error"), true) 34 | assertEq(t, stdout.Len(), 0) 35 | } 36 | 37 | func TestCases(t *testing.T) { 38 | outs, err := filepath.Glob("testdata/case*_out_*") 39 | assertEq(t, err, nil) 40 | for _, out := range outs { 41 | t.Log(out) 42 | parts := strings.SplitN(out, "_out_", 2) 43 | flags := strings.SplitN(parts[1], ".", 2) 44 | ins, err := filepath.Glob(parts[0] + "_in.*") 45 | assertEq(t, err, nil) 46 | stdout, stderr, code := run(rdfile(t, ins[0]), flags[0]) 47 | assertEq(t, string(stderr), "") 48 | assertEq(t, code, 0) 49 | assertEq(t, string(rdfile(t, out)), string(stdout)) 50 | } 51 | } 52 | 53 | func run(in []byte, flags ...string) (stdout, stderr []byte, code int) { 54 | out, err := &bytes.Buffer{}, &bytes.Buffer{} 55 | code = main.Run(bytes.NewReader(in), out, err, append([]string{"yj"}, flags...)) 56 | return out.Bytes(), err.Bytes(), code 57 | } 58 | 59 | func rdfile(t *testing.T, filename string) []byte { 60 | b, err := ioutil.ReadFile(filename) 61 | assertEq(t, err, nil) 62 | return b 63 | } 64 | 65 | type errReader struct{} 66 | 67 | func (e *errReader) Read(p []byte) (n int, err error) { 68 | return 0, errors.New("some reader error") 69 | } 70 | 71 | func assertEq(t *testing.T, a, b interface{}) { 72 | t.Helper() 73 | if !reflect.DeepEqual(a, b) { 74 | t.Fatalf("\nAssertion failed:\n\t%#v\nnot equal to\n\t%#v\n", a, b) 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /order/map.go: -------------------------------------------------------------------------------- 1 | package order 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "fmt" 7 | "reflect" 8 | "strconv" 9 | 10 | goyaml "gopkg.in/yaml.v3" 11 | ) 12 | 13 | type MapSlice []MapItem 14 | 15 | type MapItem struct { 16 | Key, Val interface{} 17 | } 18 | 19 | func (m MapSlice) Merge(in MapSlice) MapSlice { 20 | t := make(map[interface{}]struct{}, len(in)) 21 | for _, item := range in { 22 | t[item.Key] = struct{}{} 23 | } 24 | var out MapSlice 25 | for _, item := range m { 26 | if _, ok := t[item.Key]; !ok { 27 | out = append(out, item) 28 | } 29 | } 30 | for _, item := range in { 31 | out = append(out, item) 32 | } 33 | return out 34 | } 35 | 36 | var MapSliceEscapeHTML = false 37 | 38 | func (m MapSlice) MarshalJSON() ([]byte, error) { 39 | buf := &bytes.Buffer{} 40 | buf.Write([]byte{'{'}) 41 | for i, item := range m { 42 | ibuf := &bytes.Buffer{} 43 | enc := json.NewEncoder(ibuf) 44 | enc.SetEscapeHTML(MapSliceEscapeHTML) 45 | if err := enc.Encode(&item.Val); err != nil { 46 | return nil, err 47 | } 48 | buf.WriteString(fmt.Sprintf("%q:", fmt.Sprint(item.Key))) 49 | buf.Write(ibuf.Bytes()) 50 | if i < len(m)-1 { 51 | buf.Write([]byte{','}) 52 | } 53 | } 54 | buf.Write([]byte{'}'}) 55 | return buf.Bytes(), nil 56 | } 57 | 58 | func (m MapSlice) MarshalYAML() (interface{}, error) { 59 | var node goyaml.Node 60 | if err := node.Encode(map[string]interface{}{}); err != nil { 61 | return nil, err 62 | } 63 | node.Style = 0 64 | node.Content = make([]*goyaml.Node, 0, len(m)*2) 65 | for _, item := range m { 66 | var knode, vnode goyaml.Node 67 | if err := knode.Encode(item.Key); err != nil { 68 | return nil, err 69 | } 70 | if err := vnode.Encode(item.Val); err != nil { 71 | return nil, err 72 | } 73 | node.Content = append(node.Content, &knode, &vnode) 74 | } 75 | return &node, nil 76 | } 77 | 78 | func (m MapSlice) Struct() (interface{}, error) { 79 | fields := make([]reflect.StructField, 0, len(m)) 80 | 81 | for i, item := range m { 82 | key, ok := item.Key.(string) 83 | if !ok { 84 | return nil, fmt.Errorf("non-string key: %#v", item.Key) 85 | } 86 | typ := reflect.TypeOf(item.Val) 87 | if typ == nil { 88 | typ = reflect.TypeOf((*interface{})(nil)).Elem() 89 | } 90 | fields = append(fields, reflect.StructField{ 91 | Name: alphaIndex(uint64(i)), 92 | Type: typ, 93 | Tag: reflect.StructTag("toml:" + strconv.Quote(key)), 94 | }) 95 | } 96 | v := reflect.New(reflect.StructOf(fields)).Elem() 97 | for i, item := range m { 98 | if item.Val == nil { 99 | continue 100 | } 101 | v.Field(i).Set(reflect.ValueOf(item.Val)) 102 | } 103 | 104 | return v.Addr().Interface(), nil 105 | } 106 | 107 | func alphaIndex(i uint64) string { 108 | buf := &bytes.Buffer{} 109 | alphaIndexBuf(i, buf) 110 | return buf.String() 111 | } 112 | 113 | func alphaIndexBuf(i uint64, buf *bytes.Buffer) { 114 | const base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 115 | 116 | n := uint64(len(base)) 117 | if i/n != 0 { 118 | alphaIndexBuf(i/n, buf) 119 | } 120 | buf.WriteByte(base[i%n]) 121 | } 122 | -------------------------------------------------------------------------------- /testdata/case1_in.json: -------------------------------------------------------------------------------- 1 | { 2 | "0": 0, 3 | "1.0": 1.0, 4 | "1.1": 1.1, 5 | "\"key\"": "\"value\"", 6 | "<": ">", 7 | "{\"<\":\">\"}": ">", 8 | "{\"key\":\"value\"}": "value", 9 | "Infinity": "Infinity", 10 | "-Infinity": "-Infinity", 11 | "NaN": "NaN", 12 | "{\"Infinity\":\"Infinity\"}": "Infinity", 13 | "{\"-Infinity\":\"-Infinity\"}": "-Infinity", 14 | "{\"NaN\":\"NaN\"}": "NaN", 15 | "key-null": null, 16 | "key-obj-list": [ 17 | { 18 | "key-string": "value-string", 19 | "key-number": 2 20 | } 21 | ], 22 | "key-number-list": [0, 1, 1.0, 1.1], 23 | "key-string-list": ["a", "b"] 24 | } 25 | -------------------------------------------------------------------------------- /testdata/case1_out_jc.hcl: -------------------------------------------------------------------------------- 1 | "0" = 0 2 | 3 | "1.0" = 1 4 | 5 | "1.1" = 1.1 6 | 7 | "\"key\"" = "\"value\"" 8 | 9 | "<" = ">" 10 | 11 | "{\"<\":\">\"}" = ">" 12 | 13 | "{\"key\":\"value\"}" = "value" 14 | 15 | "Infinity" = "Infinity" 16 | 17 | "-Infinity" = "-Infinity" 18 | 19 | "NaN" = "NaN" 20 | 21 | "{\"Infinity\":\"Infinity\"}" = "Infinity" 22 | 23 | "{\"-Infinity\":\"-Infinity\"}" = "-Infinity" 24 | 25 | "{\"NaN\":\"NaN\"}" = "NaN" 26 | 27 | "key-null" = 28 | 29 | "key-obj-list" = { 30 | "key-string" = "value-string" 31 | 32 | "key-number" = 2 33 | } 34 | 35 | "key-number-list" = [0, 1, 1, 1.1] 36 | 37 | "key-string-list" = ["a", "b"] -------------------------------------------------------------------------------- /testdata/case1_out_jjie.json: -------------------------------------------------------------------------------- 1 | { 2 | "0": 0, 3 | "1.0": 1, 4 | "1.1": 1.1, 5 | "\"key\"": "\"value\"", 6 | "\u003c": "\u003e", 7 | "{\"\u003c\":\"\u003e\"}": "\u003e", 8 | "{\"key\":\"value\"}": "value", 9 | "Infinity": "Infinity", 10 | "-Infinity": "-Infinity", 11 | "NaN": "NaN", 12 | "{\"Infinity\":\"Infinity\"}": "Infinity", 13 | "{\"-Infinity\":\"-Infinity\"}": "-Infinity", 14 | "{\"NaN\":\"NaN\"}": "NaN", 15 | "key-null": null, 16 | "key-obj-list": [ 17 | { 18 | "key-string": "value-string", 19 | "key-number": 2 20 | } 21 | ], 22 | "key-number-list": [ 23 | 0, 24 | 1, 25 | 1, 26 | 1.1 27 | ], 28 | "key-string-list": [ 29 | "a", 30 | "b" 31 | ] 32 | } 33 | -------------------------------------------------------------------------------- /testdata/case1_out_jt.toml: -------------------------------------------------------------------------------- 1 | 0 = 0 2 | "1.0" = 1.0 3 | "1.1" = 1.1 4 | "\"key\"" = "\"value\"" 5 | "<" = ">" 6 | "{\"<\":\">\"}" = ">" 7 | "{\"key\":\"value\"}" = "value" 8 | Infinity = +inf 9 | -Infinity = -inf 10 | NaN = nan 11 | "{\"Infinity\":\"Infinity\"}" = +inf 12 | "{\"-Infinity\":\"-Infinity\"}" = -inf 13 | "{\"NaN\":\"NaN\"}" = nan 14 | key-number-list = [0, 1, 1.0, 1.1] 15 | key-string-list = ["a", "b"] 16 | 17 | [[key-obj-list]] 18 | key-string = "value-string" 19 | key-number = 2 20 | -------------------------------------------------------------------------------- /testdata/case1_out_jy.yml: -------------------------------------------------------------------------------- 1 | "0": 0 2 | "1.0": 1.0 3 | "1.1": 1.1 4 | '"key"': '"value"' 5 | <: '>' 6 | '{"<":">"}': '>' 7 | '{"key":"value"}': value 8 | .inf: .inf 9 | -.inf: -.inf 10 | .nan: .nan 11 | '{"Infinity":"Infinity"}': .inf 12 | '{"-Infinity":"-Infinity"}': -.inf 13 | '{"NaN":"NaN"}': .nan 14 | key-null: null 15 | key-obj-list: 16 | - key-string: value-string 17 | key-number: 2 18 | key-number-list: 19 | - 0 20 | - 1 21 | - 1.0 22 | - 1.1 23 | key-string-list: 24 | - a 25 | - b 26 | -------------------------------------------------------------------------------- /testdata/case1_out_jyk.yml: -------------------------------------------------------------------------------- 1 | 0: 0 2 | 1.0: 1.0 3 | 1.1: 1.1 4 | key: '"value"' 5 | <: '>' 6 | ? <: '>' 7 | : '>' 8 | ? key: value 9 | : value 10 | .inf: .inf 11 | -.inf: -.inf 12 | .nan: .nan 13 | ? .inf: .inf 14 | : .inf 15 | ? -.inf: -.inf 16 | : -.inf 17 | ? .nan: .nan 18 | : .nan 19 | key-null: null 20 | key-obj-list: 21 | - key-string: value-string 22 | key-number: 2 23 | key-number-list: 24 | - 0 25 | - 1 26 | - 1.0 27 | - 1.1 28 | key-string-list: 29 | - a 30 | - b 31 | -------------------------------------------------------------------------------- /testdata/case1_out_jyn.yml: -------------------------------------------------------------------------------- 1 | "0": 0 2 | "1.0": 1.0 3 | "1.1": 1.1 4 | '"key"': '"value"' 5 | <: '>' 6 | '{"<":">"}': '>' 7 | '{"key":"value"}': value 8 | Infinity: Infinity 9 | -Infinity: -Infinity 10 | NaN: NaN 11 | '{"Infinity":"Infinity"}': Infinity 12 | '{"-Infinity":"-Infinity"}': -Infinity 13 | '{"NaN":"NaN"}': NaN 14 | key-null: null 15 | key-obj-list: 16 | - key-string: value-string 17 | key-number: 2 18 | key-number-list: 19 | - 0 20 | - 1 21 | - 1.0 22 | - 1.1 23 | key-string-list: 24 | - a 25 | - b 26 | -------------------------------------------------------------------------------- /testdata/case2_in.yml: -------------------------------------------------------------------------------- 1 | 0: 0 2 | 1.0: 1.0 3 | 1.1: 1.1 4 | '"key"': '"value"' 5 | <: '>' 6 | ? <: '>' 7 | : '>' 8 | ? key: value 9 | : value 10 | .inf: .inf 11 | -.inf: -.inf 12 | .nan: .nan 13 | ? .inf: .inf 14 | : .inf 15 | ? -.inf: -.inf 16 | : -.inf 17 | ? .nan: .nan 18 | : .nan 19 | key-null: null 20 | key-obj-list: 21 | - key-string: value-string 22 | key-number: 2 23 | key-number-list: 24 | - !!float 0 25 | - !!float 1 26 | - 1.0 27 | - 1.1 28 | key-string-list: 29 | - a 30 | - b 31 | -------------------------------------------------------------------------------- /testdata/case2_out_yc.hcl: -------------------------------------------------------------------------------- 1 | "0" = 0 2 | 3 | "1" = 1 4 | 5 | "1.1" = 1.1 6 | 7 | "\"key\"" = "\"value\"" 8 | 9 | "<" = ">" 10 | 11 | "{\"<\":\">\"}" = ">" 12 | 13 | "{\"key\":\"value\"}" = "value" 14 | 15 | "Infinity" = "Infinity" 16 | 17 | "-Infinity" = "-Infinity" 18 | 19 | "NaN" = "NaN" 20 | 21 | "{\"Infinity\":\"Infinity\"}" = "Infinity" 22 | 23 | "{\"-Infinity\":\"-Infinity\"}" = "-Infinity" 24 | 25 | "{\"NaN\":\"NaN\"}" = "NaN" 26 | 27 | "key-null" = 28 | 29 | "key-obj-list" = { 30 | "key-string" = "value-string" 31 | 32 | "key-number" = 2 33 | } 34 | 35 | "key-number-list" = [0, 1, 1, 1.1] 36 | 37 | "key-string-list" = ["a", "b"] -------------------------------------------------------------------------------- /testdata/case2_out_yji.json: -------------------------------------------------------------------------------- 1 | { 2 | "0": 0, 3 | "1": 1, 4 | "1.1": 1.1, 5 | "\"key\"": "\"value\"", 6 | "<": ">", 7 | "{\"<\":\">\"}": ">", 8 | "{\"key\":\"value\"}": "value", 9 | "Infinity": "Infinity", 10 | "-Infinity": "-Infinity", 11 | "NaN": "NaN", 12 | "{\"Infinity\":\"Infinity\"}": "Infinity", 13 | "{\"-Infinity\":\"-Infinity\"}": "-Infinity", 14 | "{\"NaN\":\"NaN\"}": "NaN", 15 | "key-null": null, 16 | "key-obj-list": [ 17 | { 18 | "key-string": "value-string", 19 | "key-number": 2 20 | } 21 | ], 22 | "key-number-list": [ 23 | 0, 24 | 1, 25 | 1, 26 | 1.1 27 | ], 28 | "key-string-list": [ 29 | "a", 30 | "b" 31 | ] 32 | } 33 | -------------------------------------------------------------------------------- /testdata/case2_out_yjie.json: -------------------------------------------------------------------------------- 1 | { 2 | "0": 0, 3 | "1": 1, 4 | "1.1": 1.1, 5 | "\"key\"": "\"value\"", 6 | "\u003c": "\u003e", 7 | "{\"\\u003c\":\"\\u003e\"}": "\u003e", 8 | "{\"key\":\"value\"}": "value", 9 | "Infinity": "Infinity", 10 | "-Infinity": "-Infinity", 11 | "NaN": "NaN", 12 | "{\"Infinity\":\"Infinity\"}": "Infinity", 13 | "{\"-Infinity\":\"-Infinity\"}": "-Infinity", 14 | "{\"NaN\":\"NaN\"}": "NaN", 15 | "key-null": null, 16 | "key-obj-list": [ 17 | { 18 | "key-string": "value-string", 19 | "key-number": 2 20 | } 21 | ], 22 | "key-number-list": [ 23 | 0, 24 | 1, 25 | 1, 26 | 1.1 27 | ], 28 | "key-string-list": [ 29 | "a", 30 | "b" 31 | ] 32 | } 33 | -------------------------------------------------------------------------------- /testdata/case2_out_yjin.json: -------------------------------------------------------------------------------- 1 | { 2 | "0": 0, 3 | "1": 1, 4 | "1.1": 1.1, 5 | "\"key\"": "\"value\"", 6 | "<": ">", 7 | "{\"<\":\">\"}": ">", 8 | "{\"key\":\"value\"}": "value", 9 | "1.7976931348623157e+308": 1.7976931348623157e+308, 10 | "-1.7976931348623157e+308": -1.7976931348623157e+308, 11 | "null": null, 12 | "{\"1.7976931348623157e+308\":1.7976931348623157e+308}": 1.7976931348623157e+308, 13 | "{\"-1.7976931348623157e+308\":-1.7976931348623157e+308}": -1.7976931348623157e+308, 14 | "{\"null\":null}": null, 15 | "key-null": null, 16 | "key-obj-list": [ 17 | { 18 | "key-string": "value-string", 19 | "key-number": 2 20 | } 21 | ], 22 | "key-number-list": [ 23 | 0, 24 | 1, 25 | 1, 26 | 1.1 27 | ], 28 | "key-string-list": [ 29 | "a", 30 | "b" 31 | ] 32 | } 33 | -------------------------------------------------------------------------------- /testdata/case2_out_yt.toml: -------------------------------------------------------------------------------- 1 | 0 = 0 2 | 1 = 1.0 3 | "1.1" = 1.1 4 | "\"key\"" = "\"value\"" 5 | "<" = ">" 6 | "{\"<\":\">\"}" = ">" 7 | "{\"key\":\"value\"}" = "value" 8 | Infinity = +inf 9 | -Infinity = -inf 10 | NaN = nan 11 | "{\"Infinity\":\"Infinity\"}" = +inf 12 | "{\"-Infinity\":\"-Infinity\"}" = -inf 13 | "{\"NaN\":\"NaN\"}" = nan 14 | key-number-list = [0.0, 1.0, 1.0, 1.1] 15 | key-string-list = ["a", "b"] 16 | 17 | [[key-obj-list]] 18 | key-string = "value-string" 19 | key-number = 2 20 | -------------------------------------------------------------------------------- /testdata/case3_in.toml: -------------------------------------------------------------------------------- 1 | # TODO: test with -n 2 | 3 | 0 = 0 4 | 1 = 1.0 5 | "1.1" = 1.1 6 | "\"key\"" = "\"value\"" 7 | "<" = ">" 8 | '{"<":">"}' = ">" 9 | '{"key":"value"}' = "value" 10 | Infinity = inf 11 | -Infinity = -inf 12 | "+Infinity" = +inf 13 | NaN = nan 14 | -NaN = -nan 15 | "+NaN" = +nan 16 | '{"Infinity":"Infinity"}' = inf 17 | '{"-Infinity":"-Infinity"}' = -inf 18 | '{"NaN":"NaN"}' = nan 19 | key-number-list = [0.0, 1.0, 1.1] 20 | key-string-list = ["a", "b"] 21 | date = 2006-01-02T15:04:05-07:00 22 | 23 | [[key-obj-list]] 24 | key-string = "value-string" 25 | key-number = 2 26 | -------------------------------------------------------------------------------- /testdata/case3_out_tc.hcl: -------------------------------------------------------------------------------- 1 | "0" = 0 2 | 3 | "1" = 1 4 | 5 | "1.1" = 1.1 6 | 7 | "\"key\"" = "\"value\"" 8 | 9 | "<" = ">" 10 | 11 | "{\"<\":\">\"}" = ">" 12 | 13 | "{\"key\":\"value\"}" = "value" 14 | 15 | "Infinity" = "Infinity" 16 | 17 | "-Infinity" = "-Infinity" 18 | 19 | "+Infinity" = "Infinity" 20 | 21 | "NaN" = "NaN" 22 | 23 | "-NaN" = "NaN" 24 | 25 | "+NaN" = "NaN" 26 | 27 | "{\"Infinity\":\"Infinity\"}" = "Infinity" 28 | 29 | "{\"-Infinity\":\"-Infinity\"}" = "-Infinity" 30 | 31 | "{\"NaN\":\"NaN\"}" = "NaN" 32 | 33 | "key-number-list" = [0, 1, 1.1] 34 | 35 | "key-string-list" = ["a", "b"] 36 | 37 | "date" = "2006-01-02T15:04:05-07:00" 38 | 39 | "key-obj-list" = { 40 | "key-string" = "value-string" 41 | 42 | "key-number" = 2 43 | } -------------------------------------------------------------------------------- /testdata/case3_out_tji.json: -------------------------------------------------------------------------------- 1 | { 2 | "0": 0, 3 | "1": 1, 4 | "1.1": 1.1, 5 | "\"key\"": "\"value\"", 6 | "<": ">", 7 | "{\"<\":\">\"}": ">", 8 | "{\"key\":\"value\"}": "value", 9 | "Infinity": "Infinity", 10 | "-Infinity": "-Infinity", 11 | "+Infinity": "Infinity", 12 | "NaN": "NaN", 13 | "-NaN": "NaN", 14 | "+NaN": "NaN", 15 | "{\"Infinity\":\"Infinity\"}": "Infinity", 16 | "{\"-Infinity\":\"-Infinity\"}": "-Infinity", 17 | "{\"NaN\":\"NaN\"}": "NaN", 18 | "key-number-list": [ 19 | 0, 20 | 1, 21 | 1.1 22 | ], 23 | "key-string-list": [ 24 | "a", 25 | "b" 26 | ], 27 | "date": "2006-01-02T15:04:05-07:00", 28 | "key-obj-list": [ 29 | { 30 | "key-string": "value-string", 31 | "key-number": 2 32 | } 33 | ] 34 | } 35 | -------------------------------------------------------------------------------- /testdata/case3_out_tjie.json: -------------------------------------------------------------------------------- 1 | { 2 | "0": 0, 3 | "1": 1, 4 | "1.1": 1.1, 5 | "\"key\"": "\"value\"", 6 | "\u003c": "\u003e", 7 | "{\"\u003c\":\"\u003e\"}": "\u003e", 8 | "{\"key\":\"value\"}": "value", 9 | "Infinity": "Infinity", 10 | "-Infinity": "-Infinity", 11 | "+Infinity": "Infinity", 12 | "NaN": "NaN", 13 | "-NaN": "NaN", 14 | "+NaN": "NaN", 15 | "{\"Infinity\":\"Infinity\"}": "Infinity", 16 | "{\"-Infinity\":\"-Infinity\"}": "-Infinity", 17 | "{\"NaN\":\"NaN\"}": "NaN", 18 | "key-number-list": [ 19 | 0, 20 | 1, 21 | 1.1 22 | ], 23 | "key-string-list": [ 24 | "a", 25 | "b" 26 | ], 27 | "date": "2006-01-02T15:04:05-07:00", 28 | "key-obj-list": [ 29 | { 30 | "key-string": "value-string", 31 | "key-number": 2 32 | } 33 | ] 34 | } 35 | -------------------------------------------------------------------------------- /testdata/case3_out_ty.yml: -------------------------------------------------------------------------------- 1 | "0": 0 2 | "1": 1.0 3 | "1.1": 1.1 4 | '"key"': '"value"' 5 | <: '>' 6 | '{"<":">"}': '>' 7 | '{"key":"value"}': value 8 | .inf: .inf 9 | -.inf: -.inf 10 | +Infinity: .inf 11 | .nan: .nan 12 | -NaN: .nan 13 | +NaN: .nan 14 | '{"Infinity":"Infinity"}': .inf 15 | '{"-Infinity":"-Infinity"}': -.inf 16 | '{"NaN":"NaN"}': .nan 17 | key-number-list: 18 | - 0.0 19 | - 1.0 20 | - 1.1 21 | key-string-list: 22 | - a 23 | - b 24 | date: 2006-01-02T15:04:05-07:00 25 | key-obj-list: 26 | - key-string: value-string 27 | key-number: 2 28 | -------------------------------------------------------------------------------- /testdata/case3_out_tyk.yml: -------------------------------------------------------------------------------- 1 | 0: 0 2 | 1: 1.0 3 | 1.1: 1.1 4 | key: '"value"' 5 | <: '>' 6 | ? <: '>' 7 | : '>' 8 | ? key: value 9 | : value 10 | .inf: .inf 11 | -.inf: -.inf 12 | +Infinity: .inf 13 | .nan: .nan 14 | -NaN: .nan 15 | +NaN: .nan 16 | ? .inf: .inf 17 | : .inf 18 | ? -.inf: -.inf 19 | : -.inf 20 | ? .nan: .nan 21 | : .nan 22 | key-number-list: 23 | - 0.0 24 | - 1.0 25 | - 1.1 26 | key-string-list: 27 | - a 28 | - b 29 | date: 2006-01-02T15:04:05-07:00 30 | key-obj-list: 31 | - key-string: value-string 32 | key-number: 2 33 | -------------------------------------------------------------------------------- /testdata/case4_in.hcl: -------------------------------------------------------------------------------- 1 | "\"key\"" = "\"value\"" 2 | 3 | "-Infinity" = "-Infinity" 4 | 5 | "0" = 0 6 | 7 | "1.0" = 1 8 | 9 | "1.1" = 1.1 10 | 11 | "<" = ">" 12 | 13 | "Infinity" = "Infinity" 14 | 15 | "NaN" = "NaN" 16 | 17 | "key-number-list" = [0.0, 1.0, 1.1] 18 | 19 | "key-obj-list" = { 20 | "key-number" = 2 21 | 22 | "key-string" = "value-string" 23 | } 24 | 25 | "key-string-list" = ["a", "b"] 26 | 27 | "{\"-Infinity\":\"-Infinity\"}" = "-Infinity" 28 | 29 | "{\"<\":\">\"}" = ">" 30 | 31 | "{\"Infinity\":\"Infinity\"}" = "Infinity" 32 | 33 | "{\"NaN\":\"NaN\"}" = "NaN" 34 | 35 | "{\"key\":\"value\"}" = "value" -------------------------------------------------------------------------------- /testdata/case4_out_cji.json: -------------------------------------------------------------------------------- 1 | { 2 | "\"key\"": "\"value\"", 3 | "-Infinity": "-Infinity", 4 | "0": 0, 5 | "1.0": 1, 6 | "1.1": 1.1, 7 | "<": ">", 8 | "Infinity": "Infinity", 9 | "NaN": "NaN", 10 | "key-number-list": [ 11 | 0, 12 | 1, 13 | 1.1 14 | ], 15 | "key-obj-list": [ 16 | { 17 | "key-number": 2, 18 | "key-string": "value-string" 19 | } 20 | ], 21 | "key-string-list": [ 22 | "a", 23 | "b" 24 | ], 25 | "{\"-Infinity\":\"-Infinity\"}": "-Infinity", 26 | "{\"<\":\">\"}": ">", 27 | "{\"Infinity\":\"Infinity\"}": "Infinity", 28 | "{\"NaN\":\"NaN\"}": "NaN", 29 | "{\"key\":\"value\"}": "value" 30 | } 31 | -------------------------------------------------------------------------------- /testdata/case4_out_ct.hcl: -------------------------------------------------------------------------------- 1 | "\"key\"" = "\"value\"" 2 | -Infinity = -inf 3 | 0 = 0 4 | "1.0" = 1 5 | "1.1" = 1.1 6 | "<" = ">" 7 | Infinity = +inf 8 | NaN = nan 9 | key-number-list = [0.0, 1.0, 1.1] 10 | key-string-list = ["a", "b"] 11 | "{\"-Infinity\":\"-Infinity\"}" = -inf 12 | "{\"<\":\">\"}" = ">" 13 | "{\"Infinity\":\"Infinity\"}" = +inf 14 | "{\"NaN\":\"NaN\"}" = nan 15 | "{\"key\":\"value\"}" = "value" 16 | 17 | [[key-obj-list]] 18 | key-number = 2 19 | key-string = "value-string" 20 | -------------------------------------------------------------------------------- /testdata/case4_out_cy.yml: -------------------------------------------------------------------------------- 1 | '"key"': '"value"' 2 | -.inf: -.inf 3 | "0": 0 4 | "1.0": 1 5 | "1.1": 1.1 6 | <: '>' 7 | .inf: .inf 8 | .nan: .nan 9 | key-number-list: 10 | - 0.0 11 | - 1.0 12 | - 1.1 13 | key-obj-list: 14 | - key-number: 2 15 | key-string: value-string 16 | key-string-list: 17 | - a 18 | - b 19 | '{"-Infinity":"-Infinity"}': -.inf 20 | '{"<":">"}': '>' 21 | '{"Infinity":"Infinity"}': .inf 22 | '{"NaN":"NaN"}': .nan 23 | '{"key":"value"}': value 24 | -------------------------------------------------------------------------------- /testdata/case4_out_cyk.yml: -------------------------------------------------------------------------------- 1 | key: '"value"' 2 | -.inf: -.inf 3 | 0: 0 4 | 1.0: 1 5 | 1.1: 1.1 6 | <: '>' 7 | .inf: .inf 8 | .nan: .nan 9 | key-number-list: 10 | - 0.0 11 | - 1.0 12 | - 1.1 13 | key-obj-list: 14 | - key-number: 2 15 | key-string: value-string 16 | key-string-list: 17 | - a 18 | - b 19 | ? -.inf: -.inf 20 | : -.inf 21 | ? <: '>' 22 | : '>' 23 | ? .inf: .inf 24 | : .inf 25 | ? .nan: .nan 26 | : .nan 27 | ? key: value 28 | : value 29 | -------------------------------------------------------------------------------- /testdata/case4_out_cyn.yml: -------------------------------------------------------------------------------- 1 | '"key"': '"value"' 2 | -Infinity: -Infinity 3 | "0": 0 4 | "1.0": 1 5 | "1.1": 1.1 6 | <: '>' 7 | Infinity: Infinity 8 | NaN: NaN 9 | key-number-list: 10 | - 0.0 11 | - 1.0 12 | - 1.1 13 | key-obj-list: 14 | - key-number: 2 15 | key-string: value-string 16 | key-string-list: 17 | - a 18 | - b 19 | '{"-Infinity":"-Infinity"}': -Infinity 20 | '{"<":">"}': '>' 21 | '{"Infinity":"Infinity"}': Infinity 22 | '{"NaN":"NaN"}': NaN 23 | '{"key":"value"}': value 24 | -------------------------------------------------------------------------------- /toml/decoder.go: -------------------------------------------------------------------------------- 1 | package toml 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | 7 | gotoml "github.com/BurntSushi/toml" 8 | 9 | "github.com/sclevine/yj/v5/order" 10 | ) 11 | 12 | type Decoder struct { 13 | // If set, NaN, Inf, etc. are replaced by the set values 14 | NaN, PosInf, NegInf interface{} 15 | } 16 | 17 | func (d *Decoder) Decode(toml interface{}, keys []gotoml.Key) (normal interface{}, err error) { 18 | defer catchFailure(&err) 19 | v, _ := d.decode(toml, keys, nil, 0) 20 | return v, nil 21 | } 22 | 23 | func (d Decoder) decode(v interface{}, keys []gotoml.Key, key gotoml.Key, pos int) (interface{}, int) { 24 | switch v := v.(type) { 25 | case map[string]interface{}: 26 | ks, npos := uniqueKeys(keys, key, pos, len(v)) 27 | if len(ks) != len(v) { 28 | panic(fmt.Errorf("key mismatch, %d vs. %d", len(ks), len(v))) 29 | } 30 | out := make(order.MapSlice, 0, len(ks)) 31 | for _, k := range ks { 32 | next, ok := v[k] 33 | if !ok { 34 | panic(fmt.Errorf("missing key `%s'", k)) 35 | } 36 | val, dpos := d.decode(next, keys, append(key, k), pos) 37 | if dpos > npos { 38 | npos = dpos 39 | } 40 | out = append(out, order.MapItem{Key: k, Val: val}) 41 | } 42 | if len(keys) > npos && keysEqual(keys[npos], key) { 43 | npos++ 44 | } 45 | return out, npos 46 | case []map[string]interface{}: 47 | out := make([]interface{}, 0, len(v)) 48 | for _, item := range v { 49 | var val interface{} 50 | val, pos = d.decode(item, keys, key, pos) 51 | out = append(out, val) 52 | } 53 | return out, pos 54 | case []interface{}: 55 | out := make([]interface{}, 0, len(v)) 56 | for _, item := range v { 57 | var val interface{} 58 | val, pos = d.decode(item, keys, key, pos) 59 | out = append(out, val) 60 | } 61 | return out, pos 62 | default: 63 | return d.convert(v), pos 64 | } 65 | } 66 | 67 | func uniqueKeys(keys []gotoml.Key, prefix gotoml.Key, pos, n int) ([]string, int) { 68 | m := make(map[string]struct{}) 69 | var out []string 70 | end := pos 71 | for i, k := range keys[pos:] { 72 | if n == 0 { 73 | break 74 | } 75 | rest, ok := startsWith(k, prefix) 76 | if !ok { 77 | continue 78 | } 79 | if len(rest) == 0 { 80 | end = pos + i + 1 // actually needed? 81 | continue 82 | } 83 | r := rest[0] 84 | if _, ok := m[r]; !ok { 85 | m[r] = struct{}{} 86 | out = append(out, r) 87 | n-- 88 | end = pos + i + 1 89 | } 90 | } 91 | return out, end 92 | } 93 | 94 | func (d Decoder) convert(in interface{}) interface{} { 95 | switch in := in.(type) { 96 | case float64: 97 | switch { 98 | case d.NaN != nil && math.IsNaN(in): 99 | return d.NaN 100 | case d.PosInf != nil && math.IsInf(in, 1): 101 | return d.PosInf 102 | case d.NegInf != nil && math.IsInf(in, -1): 103 | return d.NegInf 104 | } 105 | return in 106 | } 107 | return in 108 | } 109 | 110 | func startsWith(key, prefix gotoml.Key) (rest []string, ok bool) { 111 | if len(key) < len(prefix) { 112 | return nil, false 113 | } 114 | for i := range prefix { 115 | if key[i] != prefix[i] { 116 | return nil, false 117 | } 118 | } 119 | return key[len(prefix):], true 120 | } 121 | 122 | func keysEqual(k1, k2 gotoml.Key) bool { 123 | if len(k1) != len(k2) { 124 | return false 125 | } 126 | for i := range k1 { 127 | if k1[i] != k2[i] { 128 | return false 129 | } 130 | } 131 | return true 132 | } 133 | -------------------------------------------------------------------------------- /toml/encoder.go: -------------------------------------------------------------------------------- 1 | package toml 2 | 3 | import ( 4 | "math" 5 | 6 | "github.com/sclevine/yj/v5/order" 7 | ) 8 | 9 | type Encoder struct { 10 | // If set, the set values will be converted to NaN, Inf, etc. 11 | NaN, PosInf, NegInf interface{} 12 | } 13 | 14 | func (e *Encoder) Encode(normal interface{}) (toml interface{}, err error) { 15 | defer catchFailure(&err) 16 | return e.encode(normal), nil 17 | } 18 | 19 | func (e *Encoder) encode(val interface{}) interface{} { 20 | switch val := val.(type) { 21 | case order.MapSlice: 22 | for i, item := range val { 23 | val[i].Val = e.encode(item.Val) 24 | } 25 | s, err := val.Struct() 26 | if err != nil { 27 | panic(err) 28 | } 29 | return s 30 | case []interface{}: 31 | out := make([]interface{}, 0, len(val)) 32 | for _, v := range val { 33 | if v == nil { 34 | continue 35 | } 36 | out = append(out, e.encode(v)) 37 | } 38 | return out 39 | default: 40 | return e.convert(val) 41 | } 42 | } 43 | 44 | func (e *Encoder) convert(in interface{}) interface{} { 45 | switch in { 46 | case nil: 47 | return nil 48 | case e.NaN: 49 | return math.NaN() 50 | case e.PosInf: 51 | return math.Inf(1) 52 | case e.NegInf: 53 | return math.Inf(-1) 54 | } 55 | return in 56 | } 57 | -------------------------------------------------------------------------------- /toml/util.go: -------------------------------------------------------------------------------- 1 | package toml 2 | 3 | import "fmt" 4 | 5 | // useful for catching panics in external packages 6 | func catchFailure(err *error) { 7 | if r := recover(); r != nil { 8 | var ok bool 9 | if *err, ok = r.(error); !ok { 10 | *err = fmt.Errorf("unexpected failure: %v", r) 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /yaml/decoder.go: -------------------------------------------------------------------------------- 1 | package yaml 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "math" 7 | "reflect" 8 | "strings" 9 | 10 | goyaml "gopkg.in/yaml.v3" 11 | 12 | "github.com/sclevine/yj/v5/order" 13 | ) 14 | 15 | // NOTE: some parts copied from gopkg.in/yaml.v3 16 | 17 | const ( 18 | // 400,000 decode operations is ~500kb of dense object declarations, or 19 | // ~5kb of dense object declarations with 10000% alias expansion 20 | aliasRatioRangeLow = 400000 21 | 22 | // 4,000,000 decode operations is ~5MB of dense object declarations, or 23 | // ~4.5MB of dense object declarations with 10% alias expansion 24 | aliasRatioRangeHigh = 4000000 25 | 26 | // aliasRatioRange is the range over which we scale allowed alias ratios 27 | aliasRatioRange = float64(aliasRatioRangeHigh - aliasRatioRangeLow) 28 | 29 | longTagPrefix = "tag:yaml.org,2002:" 30 | mergeTag = "!!merge" 31 | ) 32 | 33 | var ErrNotMaps = errors.New("map merge requires map or sequence of maps as the value") 34 | 35 | type Decoder struct { 36 | KeyMarshal func(interface{}) ([]byte, error) 37 | 38 | // If set, NaN, Inf, etc. are replaced by the set values 39 | NaN, PosInf, NegInf interface{} 40 | KeyNaN, KeyPosInf, KeyNegInf interface{} 41 | } 42 | 43 | // Decode decodes a YAML node tree into an the normalized object format. 44 | func (d *Decoder) Decode(node *goyaml.Node) (normal interface{}, err error) { 45 | defer catchFailure(&err) 46 | dt := decodeTracker{Decoder: d} 47 | return dt.normalize(node), nil 48 | } 49 | 50 | type decodeTracker struct { 51 | *Decoder 52 | aliases map[*goyaml.Node]struct{} 53 | doc *goyaml.Node 54 | decodeCount int 55 | aliasCount int 56 | aliasDepth int 57 | } 58 | 59 | func (d *decodeTracker) normalize(n *goyaml.Node) interface{} { 60 | d.decodeCount++ 61 | if d.aliasDepth > 0 { 62 | d.aliasCount++ 63 | } 64 | if d.aliasCount > 100 && d.decodeCount > 1000 && float64(d.aliasCount)/float64(d.decodeCount) > allowedAliasRatio(d.decodeCount) { 65 | panic(fmt.Errorf("document contains excessive aliasing")) 66 | } 67 | 68 | switch n.Kind { 69 | case goyaml.DocumentNode: 70 | return d.document(n) 71 | case goyaml.AliasNode: 72 | return d.alias(n) 73 | case goyaml.ScalarNode: 74 | var out interface{} 75 | if err := n.Decode(&out); err != nil { 76 | panic(fmt.Errorf("scalar decode error: %s", err)) 77 | } 78 | switch out := out.(type) { 79 | case float64: 80 | return d.float(out) 81 | } 82 | return d.other(out) 83 | case goyaml.MappingNode: 84 | return d.mapping(n) 85 | case goyaml.SequenceNode: 86 | return d.sequence(n) 87 | case 0: 88 | if n.IsZero() { 89 | return nil 90 | } 91 | fallthrough 92 | default: 93 | panic(fmt.Errorf("cannot decode node with unknown kind %d", n.Kind)) 94 | } 95 | } 96 | 97 | func (d *decodeTracker) other(in interface{}) interface{} { 98 | switch reflect.ValueOf(in).Kind() { 99 | case reflect.Map, reflect.Array, reflect.Slice, reflect.Float32: 100 | panic(fmt.Errorf("unexpected type: %#v", in)) 101 | } 102 | return in 103 | } 104 | 105 | func (d *decodeTracker) float(in float64) interface{} { 106 | switch { 107 | case d.NaN != nil && math.IsNaN(in): 108 | return d.NaN 109 | case d.PosInf != nil && math.IsInf(in, 1): 110 | return d.PosInf 111 | case d.NegInf != nil && math.IsInf(in, -1): 112 | return d.NegInf 113 | } 114 | return in 115 | } 116 | 117 | func (d *decodeTracker) key(n *goyaml.Node) string { 118 | // Decoder remains reentrant, but decodeTracker need not be 119 | defer func(dec *Decoder) { 120 | d.Decoder = dec 121 | }(d.Decoder) 122 | kdec := *d.Decoder 123 | kdec.NaN = d.KeyNaN 124 | kdec.PosInf = d.KeyPosInf 125 | kdec.NegInf = d.KeyNegInf 126 | d.Decoder = &kdec 127 | switch key := d.normalize(n).(type) { 128 | case string: 129 | return key 130 | case fmt.Stringer: 131 | return key.String() 132 | default: 133 | out, err := d.KeyMarshal(key) 134 | if err != nil { 135 | panic(err) 136 | } 137 | return string(out) 138 | } 139 | } 140 | 141 | func allowedAliasRatio(decodeCount int) float64 { 142 | switch { 143 | case decodeCount <= aliasRatioRangeLow: 144 | // allow 99% to come from alias expansion for small-to-medium documents 145 | return 0.99 146 | case decodeCount >= aliasRatioRangeHigh: 147 | // allow 10% to come from alias expansion for very large documents 148 | return 0.10 149 | default: 150 | // scale smoothly from 99% down to 10% over the range. 151 | // this maps to 396,000 - 400,000 allowed alias-driven decodes over the range. 152 | // 400,000 decode operations is ~100MB of allocations in worst-case scenarios (single-item maps). 153 | return 0.99 - 0.89*(float64(decodeCount-aliasRatioRangeLow)/aliasRatioRange) 154 | } 155 | } 156 | 157 | func (d *decodeTracker) document(n *goyaml.Node) interface{} { 158 | if len(n.Content) != 1 { 159 | panic(fmt.Errorf("invalid document")) 160 | } 161 | d.doc = n 162 | return d.normalize(n.Content[0]) 163 | } 164 | 165 | func (d *decodeTracker) alias(n *goyaml.Node) interface{} { 166 | if d.aliases == nil { 167 | d.aliases = make(map[*goyaml.Node]struct{}) 168 | } 169 | if _, ok := d.aliases[n]; ok { 170 | // TODO this could actually be allowed in some circumstances. 171 | panic(fmt.Errorf("anchor '%s' value contains itself", n.Value)) 172 | } 173 | d.aliases[n] = struct{}{} 174 | d.aliasDepth++ 175 | out := d.normalize(n.Alias) 176 | d.aliasDepth-- 177 | delete(d.aliases, n) 178 | return out 179 | } 180 | 181 | func (d *decodeTracker) sequence(n *goyaml.Node) []interface{} { 182 | out := make([]interface{}, 0, len(n.Content)) 183 | for _, c := range n.Content { 184 | out = append(out, d.normalize(c)) 185 | } 186 | return out 187 | } 188 | 189 | func shortTag(tag string) string { 190 | // TODO This can easily be made faster and produce less garbage. 191 | if strings.HasPrefix(tag, longTagPrefix) { 192 | return "!!" + tag[len(longTagPrefix):] 193 | } 194 | return tag 195 | } 196 | 197 | func isMerge(n *goyaml.Node) bool { 198 | return n.Kind == goyaml.ScalarNode && n.Value == "<<" && (n.Tag == "" || n.Tag == "!" || shortTag(n.Tag) == mergeTag) 199 | } 200 | 201 | func (d *decodeTracker) mapping(n *goyaml.Node) order.MapSlice { 202 | l := len(n.Content) 203 | out := make(order.MapSlice, 0, l/2) 204 | 205 | for i := 0; i < l; i += 2 { 206 | if isMerge(n.Content[i]) { 207 | out = d.merge(out, n.Content[i+1]) 208 | continue 209 | } 210 | out = append(out, order.MapItem{ 211 | Key: d.key(n.Content[i]), 212 | Val: d.normalize(n.Content[i+1]), 213 | }) 214 | } 215 | return out 216 | } 217 | 218 | func (d *decodeTracker) merge(m order.MapSlice, n *goyaml.Node) order.MapSlice { 219 | switch n.Kind { 220 | case goyaml.AliasNode: 221 | if n.Alias != nil && n.Alias.Kind != goyaml.MappingNode { 222 | panic(ErrNotMaps) 223 | } 224 | fallthrough 225 | case goyaml.MappingNode: 226 | in, ok := d.normalize(n).(order.MapSlice) 227 | if !ok { 228 | panic(ErrNotMaps) 229 | } 230 | return m.Merge(in) 231 | case goyaml.SequenceNode: 232 | // Step backwards as earlier nodes take precedence. 233 | for i := len(n.Content) - 1; i >= 0; i-- { 234 | ni := n.Content[i] 235 | if ni.Kind == goyaml.AliasNode { 236 | if ni.Alias != nil && ni.Alias.Kind != goyaml.MappingNode { 237 | panic(ErrNotMaps) 238 | } 239 | } else if ni.Kind != goyaml.MappingNode { 240 | panic(ErrNotMaps) 241 | } 242 | in, ok := d.normalize(n).(order.MapSlice) 243 | if !ok { 244 | panic(ErrNotMaps) 245 | } 246 | m = m.Merge(in) 247 | } 248 | return m 249 | default: 250 | panic(ErrNotMaps) 251 | } 252 | } 253 | -------------------------------------------------------------------------------- /yaml/encoder.go: -------------------------------------------------------------------------------- 1 | package yaml 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | "reflect" 7 | "strconv" 8 | "unicode" 9 | 10 | "gopkg.in/yaml.v3" 11 | 12 | "github.com/sclevine/yj/v5/order" 13 | ) 14 | 15 | type Encoder struct { 16 | KeyUnmarshal func([]byte, interface{}) error 17 | 18 | // If set, the set values will be converted to NaN, Inf, etc. 19 | NaN, PosInf, NegInf interface{} 20 | KeyNaN, KeyPosInf, KeyNegInf interface{} 21 | } 22 | 23 | // Encode encodes the normalized object format into a suitable format for marshaling to YAML. 24 | func (e *Encoder) Encode(normal interface{}) (yaml interface{}, err error) { 25 | defer catchFailure(&err) 26 | return e.denormalize(normal), nil 27 | } 28 | 29 | func (e *Encoder) denormalize(in interface{}) interface{} { 30 | switch in := in.(type) { 31 | case order.MapSlice: 32 | out := make(order.MapSlice, 0, len(in)) 33 | for _, item := range in { 34 | key, ok := item.Key.(string) 35 | if !ok { 36 | panic(fmt.Errorf("key not string: %#v", item.Key)) 37 | } 38 | out = append(out, order.MapItem{ 39 | Key: e.key(key), 40 | Val: e.denormalize(item.Val), 41 | }) 42 | } 43 | return out 44 | case []interface{}: 45 | out := make([]interface{}, 0, len(in)) 46 | for _, v := range in { 47 | out = append(out, e.denormalize(v)) 48 | } 49 | return out 50 | default: 51 | return e.other(in) 52 | } 53 | } 54 | 55 | func (e *Encoder) other(in interface{}) interface{} { 56 | switch in { 57 | case nil: 58 | return nil 59 | case e.NaN: 60 | return math.NaN() 61 | case e.PosInf: 62 | return math.Inf(1) 63 | case e.NegInf: 64 | return math.Inf(-1) 65 | } 66 | switch reflect.ValueOf(in).Kind() { 67 | case reflect.Map, reflect.Array, reflect.Slice, reflect.Float32: 68 | panic(fmt.Errorf("unexpected type: %#v", in)) 69 | case reflect.Float64: 70 | out := strconv.FormatFloat(in.(float64), 'g', -1, 64) 71 | if isNumbers(out) { 72 | return &yaml.Node{Kind: yaml.ScalarNode, Value: out + ".0"} 73 | } 74 | } 75 | return in 76 | } 77 | 78 | func isNumbers(s string) bool { 79 | if len(s) == 0 { 80 | return false 81 | } 82 | for _, r := range s { 83 | if !unicode.IsNumber(r) { 84 | return false 85 | } 86 | } 87 | return true 88 | } 89 | 90 | func (e *Encoder) key(in string) interface{} { 91 | var key interface{} = in 92 | if e.KeyUnmarshal != nil { 93 | var v interface{} 94 | if err := e.KeyUnmarshal([]byte(in), &v); err == nil { 95 | key = v 96 | } 97 | } 98 | kenc := *e 99 | kenc.NaN = e.KeyNaN 100 | kenc.PosInf = e.KeyPosInf 101 | kenc.NegInf = e.KeyNegInf 102 | switch out := kenc.denormalize(key); reflect.ValueOf(out).Kind() { 103 | case reflect.Map, reflect.Slice, reflect.Func: 104 | return &out 105 | default: 106 | return out 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /yaml/json.go: -------------------------------------------------------------------------------- 1 | package yaml 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "errors" 7 | "reflect" 8 | 9 | goyaml "gopkg.in/yaml.v3" 10 | ) 11 | 12 | type KeyJSON struct { 13 | EscapeHTML bool 14 | } 15 | 16 | func (k *KeyJSON) Marshal(v interface{}) ([]byte, error) { 17 | keyJSON := &bytes.Buffer{} 18 | jsonEnc := json.NewEncoder(keyJSON) 19 | jsonEnc.SetEscapeHTML(k.EscapeHTML) 20 | if err := jsonEnc.Encode(v); err != nil { 21 | return nil, err 22 | } 23 | return keyJSON.Bytes()[:keyJSON.Len()-1], nil 24 | } 25 | 26 | func (k *KeyJSON) Unmarshal(src []byte, v interface{}) error { 27 | if !json.Valid(src) { 28 | var null interface{} 29 | err := json.Unmarshal(src, &null) 30 | if err == nil { 31 | err = errors.New("invalid JSON") 32 | } 33 | return err 34 | } 35 | r := bytes.NewReader(src) 36 | var node goyaml.Node 37 | if err := goyaml.NewDecoder(r).Decode(&node); err != nil { 38 | return err 39 | } 40 | dec := &Decoder{} 41 | out, err := dec.Decode(&node) 42 | if err != nil { 43 | return err 44 | } 45 | val := reflect.ValueOf(v).Elem() 46 | if !val.CanSet() { 47 | return errors.New("cannot set value") 48 | } 49 | val.Set(reflect.ValueOf(out)) 50 | return nil 51 | } 52 | -------------------------------------------------------------------------------- /yaml/util.go: -------------------------------------------------------------------------------- 1 | package yaml 2 | 3 | import "fmt" 4 | 5 | func catchFailure(err *error) { 6 | if r := recover(); r != nil { 7 | var ok bool 8 | if *err, ok = r.(error); !ok { 9 | *err = fmt.Errorf("unexpected failure: %v", r) 10 | } 11 | } 12 | } 13 | --------------------------------------------------------------------------------