From eeb16443d4a436c3d2ed77505ebfcab0cd01081e Mon Sep 17 00:00:00 2001 From: Mike Farah Date: Tue, 29 Sep 2015 10:56:28 +1000 Subject: [PATCH] Can update simple properties (to stdout) --- yaml.go | 26 ++++++++++++++++++++++++++ yaml_test.go | 11 +++++++++++ 2 files changed, 37 insertions(+) diff --git a/yaml.go b/yaml.go index ff15e965..d116fb87 100644 --- a/yaml.go +++ b/yaml.go @@ -22,6 +22,12 @@ func main() { Usage: "read \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 \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 { diff --git a/yaml_test.go b/yaml_test.go index ce53d7b9..4f276887 100644 --- a/yaml_test.go +++ b/yaml_test.go @@ -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) + } +}