Skip to content

Commit 364c1a8

Browse files
committed
Can update yam to stdout
1 parent 2a0290a commit 364c1a8

File tree

2 files changed

+43
-10
lines changed

2 files changed

+43
-10
lines changed

README.md

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,22 @@ yaml sample.yaml b.e.1.name
4444
```
4545
will output 'sam'
4646

47+
### Updating yaml
48+
Given a sample.yaml file of:
49+
```yaml
50+
b:
51+
c: 2
52+
```
53+
then
54+
```bash
55+
yaml w sample.yaml b.c 'cat'
56+
```
57+
will output:
58+
```yaml
59+
b:
60+
c: cat
61+
```
62+
63+
4764
## TODO
48-
* Updating yaml files
4965
* Handling '.' in path names

yaml.go

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -30,37 +30,59 @@ func main() {
3030
},
3131
}
3232
app.Action = readProperty
33+
app.Flags = []cli.Flag{
34+
cli.StringFlag{
35+
Name: "trim, t",
36+
Value: "true",
37+
Usage: "trim output",
38+
},
39+
}
3340
app.Run(os.Args)
3441
}
3542

3643
func readProperty(c *cli.Context) {
44+
3745
var parsedData map[interface{}]interface{}
46+
3847
readYaml(c, &parsedData)
3948

49+
if len(c.Args()) == 1 {
50+
printYaml(parsedData, c.Bool("trim"))
51+
os.Exit(0)
52+
}
53+
4054
var path = c.Args()[1]
4155
var paths = strings.Split(path, ".")
4256

43-
printYaml(readMap(parsedData, paths[0], paths[1:len(paths)]))
57+
printYaml(readMap(parsedData, paths[0], paths[1:len(paths)]), c.Bool("trim"))
4458
}
4559

4660
func writeProperty(c *cli.Context) {
4761
var parsedData map[interface{}]interface{}
4862
readYaml(c, &parsedData)
4963

64+
if len(c.Args()) != 3 {
65+
log.Fatalf("Must provide <filename> <path_to_update> <value>")
66+
}
67+
5068
var path = c.Args()[1]
5169
var paths = strings.Split(path, ".")
5270

5371
write(parsedData, paths[0], paths[1:len(paths)], c.Args()[2])
5472

55-
printYaml(parsedData)
73+
printYaml(parsedData, c.Bool("trim"))
5674
}
5775

58-
func printYaml(context interface{}) {
76+
func printYaml(context interface{}, trim bool) {
5977
out, err := yaml.Marshal(context)
6078
if err != nil {
6179
log.Fatalf("error printing yaml: %v", err)
6280
}
63-
fmt.Println(string(out))
81+
outStr := string(out)
82+
if trim {
83+
outStr = strings.Trim(outStr, "\n ")
84+
}
85+
fmt.Println(outStr)
6486
}
6587

6688
func readYaml(c *cli.Context, parsedData *map[interface{}]interface{}) {
@@ -69,11 +91,6 @@ func readYaml(c *cli.Context, parsedData *map[interface{}]interface{}) {
6991
}
7092
var rawData = readFile(c.Args()[0])
7193

72-
if len(c.Args()) == 1 {
73-
fmt.Println(string(rawData[:]))
74-
os.Exit(0)
75-
}
76-
7794
err := yaml.Unmarshal([]byte(rawData), &parsedData)
7895
if err != nil {
7996
log.Fatalf("error: %v", err)

0 commit comments

Comments
 (0)