From b1c670e121e7dd43f66b18295799f3af105db97d Mon Sep 17 00:00:00 2001 From: Mike Farah Date: Sun, 27 Sep 2015 13:11:10 +1000 Subject: [PATCH] First cut - can recursively read yaml! --- yaml.go | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/yaml.go b/yaml.go index 739c59da..f008ef28 100644 --- a/yaml.go +++ b/yaml.go @@ -7,6 +7,7 @@ import ( "io/ioutil" "os" "github.com/codegangsta/cli" + "strings" ) func main() { @@ -17,7 +18,7 @@ func main() { { Name: "read", Aliases: []string{"r"}, - Usage: "(default) reads a property from a given yaml file", + Usage: "read \n\te.g.: yaml read sample.json a.b.c\n\t(default) reads a property from a given yaml file", Action: read_file, }, } @@ -31,17 +32,31 @@ func read_file(c *cli.Context) { } var filename = c.Args()[0] var raw_data, read_error = ioutil.ReadFile(filename) - if read_error != nil { log.Fatalf("error: %v", read_error) } - var parsed_data interface{} + var parsed_data map[interface{}]interface{} err := yaml.Unmarshal([]byte(raw_data), &parsed_data) if err != nil { log.Fatalf("error: %v", err) } - fmt.Println(parsed_data) + var path = c.Args()[1] + var paths = strings.Split(path, ".") + + fmt.Println(read(parsed_data, paths[0], paths[1:len(paths)])) +} + +func read(context map[interface{}]interface{}, head string, tail []string) interface{} { + value := context[head] + // fmt.Println("read called") + + switch value.(type) { + case bool, int, string, []interface{}: + return value + default: // recurse into map + return read(value.(map[interface{}]interface{}), tail[0], tail[1:len(tail)]) + } }