Handles quoted values when writing

This commit is contained in:
Mike Farah 2015-10-03 17:25:13 +10:00
parent 690442d02e
commit 8aa69fc9ba
3 changed files with 28 additions and 28 deletions

View File

@ -4,7 +4,6 @@ import (
"fmt"
"gopkg.in/yaml.v2"
"os"
"strings"
"testing"
)
@ -51,22 +50,6 @@ func TestWrite_simple(t *testing.T) {
assertResult(t, "4", b["c"].(string))
}
var getValueTests = []struct {
argument string
expectedResult interface{}
testDescription string
}{
{"true", true, "boolean"},
{"3.4", 3.4, "number"},
}
func TestGetValue(t *testing.T) {
for _, tt := range getValueTests {
assertResultWithContext(t, tt.expectedResult, getValue(tt.argument, false), tt.testDescription)
assertResultWithContext(t, tt.argument, getValue(tt.argument, true), strings.Join([]string{tt.testDescription, "with forceString"}, " "))
}
}
func assertResult(t *testing.T, expectedValue interface{}, actualValue interface{}) {
if expectedValue != actualValue {
t.Error("Expected <", expectedValue, "> but got <", actualValue, ">")

17
yaml.go
View File

@ -64,23 +64,17 @@ func writeProperty(c *cli.Context) {
log.Fatalf("Must provide <filename> <path_to_update> <value>")
}
var forceString bool
var argumentLength = len(c.Args())
if argumentLength >= 4 && c.Args()[argumentLength-1] == "forceString" {
forceString = true
}
var paths = parsePath(c.Args()[1])
write(parsedData, paths[0], paths[1:len(paths)], getValue(c.Args()[2], forceString))
write(parsedData, paths[0], paths[1:len(paths)], getValue(c.Args()[2]))
printYaml(parsedData, c.Bool("trim"))
}
func getValue(argument string, forceString bool) interface{} {
func getValue(argument string) interface{} {
var value, err interface{}
if !forceString {
var inQuotes = argument[0] == '"'
if !inQuotes {
value, err = strconv.ParseFloat(argument, 64)
if err == nil {
return value
@ -89,8 +83,9 @@ func getValue(argument string, forceString bool) interface{} {
if err == nil {
return value
}
}
return argument
}
return argument[1 : len(argument)-1]
}
func printYaml(context interface{}, trim bool) {

22
yaml_test.go Normal file
View File

@ -0,0 +1,22 @@
package main
import (
"testing"
)
var getValueTests = []struct {
argument string
expectedResult interface{}
testDescription string
}{
{"true", true, "boolean"},
{"\"true\"", "true", "boolean as string"},
{"3.4", 3.4, "number"},
{"\"3.4\"", "3.4", "number as string"},
}
func TestGetValue(t *testing.T) {
for _, tt := range getValueTests {
assertResultWithContext(t, tt.expectedResult, getValue(tt.argument), tt.testDescription)
}
}