Can update simple properties (to stdout)

This commit is contained in:
Mike Farah 2015-09-29 10:56:28 +10:00
parent eebd319246
commit eeb16443d4
2 changed files with 37 additions and 0 deletions

26
yaml.go
View File

@ -22,6 +22,12 @@ func main() {
Usage: "read <filename> <path>\n\te.g.: yaml read sample.json a.b.c\n\t(default) reads a property from a given yaml file",
Action: readProperty,
},
{
Name: "write",
Aliases: []string{"w"},
Usage: "write <filename> <path> <value>\n\te.g.: yaml write sample.json a.b.c 5\n\tupdates a property from a given yaml file, outputs to stdout",
Action: writeProperty,
},
}
app.Action = readProperty
app.Run(os.Args)
@ -37,6 +43,18 @@ func readProperty(c *cli.Context) {
printYaml(readMap(parsedData, paths[0], paths[1:len(paths)]))
}
func writeProperty(c *cli.Context) {
var parsedData map[interface{}]interface{}
readYaml(c, &parsedData)
var path = c.Args()[1]
var paths = strings.Split(path, ".")
write(parsedData, paths[0], paths[1:len(paths)], c.Args()[2])
printYaml(parsedData)
}
func printYaml(context interface{}) {
out, err := yaml.Marshal(context)
if err != nil {
@ -70,6 +88,14 @@ func readFile(filename string) []byte {
return rawData
}
func write(context map[interface{}]interface{}, head string, tail []string, value interface{}) {
// e.g. if updating a.b.c, we need to get the 'b' map...
toUpdate := readMap(context, head, tail[0:len(tail)-1]).(map[interface{}]interface{})
// and then set the 'c' key.
key := (tail[len(tail)-1])
toUpdate[key] = value
}
func readMap(context map[interface{}]interface{}, head string, tail []string) interface{} {
value := context[head]
if len(tail) > 0 {

View File

@ -39,3 +39,14 @@ func TestReadMap_array(t *testing.T) {
t.Error("Excpted 4 but got ", result)
}
}
func TestWrite_simple(t *testing.T) {
write(parsedData, "b", []string{"c"}, "4")
b := parsedData["b"].(map[interface{}]interface{})
c := b["c"].(string)
if c != "4" {
t.Error("Excepted 4 but got ", c)
}
}