diff --git a/README.md b/README.md index ac13659c..80cbb79b 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,22 @@ yaml sample.yaml b.e.1.name ``` will output 'sam' +### Updating yaml +Given a sample.yaml file of: +```yaml +b: + c: 2 +``` +then +```bash +yaml w sample.yaml b.c 'cat' +``` +will output: +```yaml +b: + c: cat +``` + + ## TODO -* Updating yaml files * Handling '.' in path names diff --git a/yaml.go b/yaml.go index 181194dd..f806fc5d 100644 --- a/yaml.go +++ b/yaml.go @@ -30,37 +30,59 @@ func main() { }, } app.Action = readProperty + app.Flags = []cli.Flag{ + cli.StringFlag{ + Name: "trim, t", + Value: "true", + Usage: "trim output", + }, + } app.Run(os.Args) } func readProperty(c *cli.Context) { + var parsedData map[interface{}]interface{} + readYaml(c, &parsedData) + if len(c.Args()) == 1 { + printYaml(parsedData, c.Bool("trim")) + os.Exit(0) + } + var path = c.Args()[1] var paths = strings.Split(path, ".") - printYaml(readMap(parsedData, paths[0], paths[1:len(paths)])) + printYaml(readMap(parsedData, paths[0], paths[1:len(paths)]), c.Bool("trim")) } func writeProperty(c *cli.Context) { var parsedData map[interface{}]interface{} readYaml(c, &parsedData) + if len(c.Args()) != 3 { + log.Fatalf("Must provide ") + } + var path = c.Args()[1] var paths = strings.Split(path, ".") write(parsedData, paths[0], paths[1:len(paths)], c.Args()[2]) - printYaml(parsedData) + printYaml(parsedData, c.Bool("trim")) } -func printYaml(context interface{}) { +func printYaml(context interface{}, trim bool) { out, err := yaml.Marshal(context) if err != nil { log.Fatalf("error printing yaml: %v", err) } - fmt.Println(string(out)) + outStr := string(out) + if trim { + outStr = strings.Trim(outStr, "\n ") + } + fmt.Println(outStr) } func readYaml(c *cli.Context, parsedData *map[interface{}]interface{}) { @@ -69,11 +91,6 @@ func readYaml(c *cli.Context, parsedData *map[interface{}]interface{}) { } var rawData = readFile(c.Args()[0]) - if len(c.Args()) == 1 { - fmt.Println(string(rawData[:])) - os.Exit(0) - } - err := yaml.Unmarshal([]byte(rawData), &parsedData) if err != nil { log.Fatalf("error: %v", err)