From 23bded0b4e070db8587a37fc508ce581dc0da6b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Gawe=C5=82?= Date: Fri, 1 Dec 2017 20:37:19 +0100 Subject: [PATCH] parser: Fix YAML maps key type Recurse through result of yaml package parsing and change all maps from map[interface{}]interface{} to map[string]interface{} making them jsonable and sortable. Fixes #2441, #4083 --- parser/frontmatter.go | 37 +++++++++++++++++++++++++++++++++++++ parser/frontmatter_test.go | 2 +- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/parser/frontmatter.go b/parser/frontmatter.go index ab56b14d14f..9e2dcb36228 100644 --- a/parser/frontmatter.go +++ b/parser/frontmatter.go @@ -201,9 +201,46 @@ func removeTOMLIdentifier(datum []byte) []byte { func HandleYAMLMetaData(datum []byte) (interface{}, error) { m := map[string]interface{}{} err := yaml.Unmarshal(datum, &m) + + // To support boolean keys, the `yaml` package unmarshals maps to + // map[interface{}]interface{}. Here we recurse through the result + // and change all maps to map[string]interface{} like we would've + // gotten from `json`. + if err == nil { + for k, v := range m { + m[k] = stringifyYAMLMapKeys(v) + } + } + return m, err } +// stringifyKeysMapValue recurses into in and changes all instances of +// map[interface{}]interface{} to map[string]interface{}. This is useful to +// work around the impedence mismatch between JSON and YAML unmarshaling that's +// described here: https://github.com/go-yaml/yaml/issues/139 +// +// Inspired by https://github.com/stripe/stripe-mock +func stringifyYAMLMapKeys(in interface{}) interface{} { + switch in := in.(type) { + case []interface{}: + res := make([]interface{}, len(in)) + for i, v := range in { + res[i] = stringifyYAMLMapKeys(v) + } + return res + case map[interface{}]interface{}: + res := make(map[string]interface{}) + for k, v := range in { + kStr, _ := k.(string) + res[kStr] = stringifyYAMLMapKeys(v) + } + return res + default: + return in + } +} + // HandleJSONMetaData unmarshals JSON-encoded datum and returns a Go interface // representing the encoded data structure. func HandleJSONMetaData(datum []byte) (interface{}, error) { diff --git a/parser/frontmatter_test.go b/parser/frontmatter_test.go index 2e5bdec5003..36592a78059 100644 --- a/parser/frontmatter_test.go +++ b/parser/frontmatter_test.go @@ -169,7 +169,7 @@ func TestHandleYAMLMetaData(t *testing.T) { }{ {nil, map[string]interface{}{}, false}, {[]byte("title: test 1"), map[string]interface{}{"title": "test 1"}, false}, - {[]byte("a: Easy!\nb:\n c: 2\n d: [3, 4]"), map[string]interface{}{"a": "Easy!", "b": map[interface{}]interface{}{"c": 2, "d": []interface{}{3, 4}}}, false}, + {[]byte("a: Easy!\nb:\n c: 2\n d: [3, 4]"), map[string]interface{}{"a": "Easy!", "b": map[string]interface{}{"c": 2, "d": []interface{}{3, 4}}}, false}, // errors {[]byte("z = not toml"), nil, true}, }