Handle nil, map[string]string, and map[interface{}]interface{} input (#103)

* Handle map[string]string and map[interface{}]interface{} input
* Handle nil values

Fixes #99
This commit is contained in:
Cameron Moore
2016-09-20 02:07:15 -05:00
committed by Thomas Pelletier
parent 67b7b944a8
commit 45932ad32d
2 changed files with 55 additions and 0 deletions
+23
View File
@@ -647,6 +647,7 @@ func TestToTomlValue(t *testing.T) {
"1979-05-27T07:32:00Z"},
{[]interface{}{"gamma", "delta"},
"[\n \"gamma\",\n \"delta\",\n]"},
{nil, ""},
} {
result := toTomlValue(item.Value, 0)
if result != item.Expect {
@@ -668,6 +669,28 @@ func TestToString(t *testing.T) {
}
}
func TestToStringMapStringString(t *testing.T) {
in := map[string]interface{}{"m": map[string]string{"v": "abc"}}
want := "\n[m]\n v = \"abc\"\n"
tree := TreeFromMap(in)
got := tree.String()
if got != want {
t.Errorf("want:\n%q\ngot:\n%q", want, got)
}
}
func TestToStringMapInterfaceInterface(t *testing.T) {
in := map[string]interface{}{"m": map[interface{}]interface{}{"v": "abc"}}
want := "\n[m]\n v = \"abc\"\n"
tree := TreeFromMap(in)
got := tree.String()
if got != want {
t.Errorf("want:\n%q\ngot:\n%q", want, got)
}
}
func assertPosition(t *testing.T, text string, ref map[string]Position) {
tree, err := Load(text)
if err != nil {
+32
View File
@@ -84,6 +84,8 @@ func toTomlValue(item interface{}, indent int) string {
result += toTomlValue(item, indent+2) + ",\n"
}
return result + tab + "]"
case nil:
return ""
default:
panic(fmt.Sprintf("unsupported value type %T: %v", value, value))
}
@@ -116,6 +118,20 @@ func (t *TomlTree) toToml(indent, keyspace string) string {
case map[string]interface{}:
sub := TreeFromMap(node)
if len(sub.Keys()) > 0 {
result += fmt.Sprintf("\n%s[%s]\n", indent, combinedKey)
}
result += sub.toToml(indent+" ", combinedKey)
case map[string]string:
sub := TreeFromMap(convertMapStringString(node))
if len(sub.Keys()) > 0 {
result += fmt.Sprintf("\n%s[%s]\n", indent, combinedKey)
}
result += sub.toToml(indent+" ", combinedKey)
case map[interface{}]interface{}:
sub := TreeFromMap(convertMapInterfaceInterface(node))
if len(sub.Keys()) > 0 {
result += fmt.Sprintf("\n%s[%s]\n", indent, combinedKey)
}
@@ -129,6 +145,22 @@ func (t *TomlTree) toToml(indent, keyspace string) string {
return result
}
func convertMapStringString(in map[string]string) map[string]interface{} {
result := make(map[string]interface{}, len(in))
for k, v := range in {
result[k] = v
}
return result
}
func convertMapInterfaceInterface(in map[interface{}]interface{}) map[string]interface{} {
result := make(map[string]interface{}, len(in))
for k, v := range in {
result[k.(string)] = v
}
return result
}
// ToString is an alias for String
func (t *TomlTree) ToString() string {
return t.String()