mirror of
https://github.com/taigrr/yq
synced 2025-01-18 04:53:17 -08:00
Compare commits
32 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
955ecc2547 | ||
|
|
1d5fbd5ad0 | ||
|
|
1605938c2c | ||
|
|
2780903b60 | ||
|
|
81672d4efe | ||
|
|
6a696c81db | ||
|
|
805729e4f7 | ||
|
|
7db31006da | ||
|
|
8409be1cdf | ||
|
|
c03c4813d4 | ||
|
|
5ee6a9b9ca | ||
|
|
8efc46deae | ||
|
|
e4d5769f29 | ||
|
|
fea6e0db3d | ||
|
|
6823d43325 | ||
|
|
da4b1a6449 | ||
|
|
3a90629822 | ||
|
|
8aa69fc9ba | ||
|
|
690442d02e | ||
|
|
d1c545cca0 | ||
|
|
c4af37ed68 | ||
|
|
01845ea923 | ||
|
|
58bdb3ed21 | ||
|
|
0cb8a47ccb | ||
|
|
35ceb01222 | ||
|
|
c1b803364a | ||
|
|
364c1a8af3 | ||
|
|
2a0290aeac | ||
|
|
4ea8d5c4ee | ||
|
|
eeb16443d4 | ||
|
|
eebd319246 | ||
|
|
5a3c3a7152 |
105
README.md
105
README.md
@@ -1,16 +1,18 @@
|
|||||||
# yaml
|
# yaml
|
||||||
yaml command line tool written in go
|
yaml is portable command line tool written in go
|
||||||
|
|
||||||
Allows you to read (and soon update) yaml files given a yaml path.
|
Allows you to read and update yaml files from bash (or whatever). All in a lovely dependency free binary!
|
||||||
|
|
||||||
## Install
|
[Download latest release](https://github.com/mikefarah/yaml/releases/latest)
|
||||||
|
|
||||||
|
or alternatively install using go get:
|
||||||
```
|
```
|
||||||
go get github.com/mikefarah/yaml
|
go get github.com/mikefarah/yaml
|
||||||
```
|
```
|
||||||
|
|
||||||
## Read examples
|
## Read examples
|
||||||
```
|
```
|
||||||
yaml <yaml file> <path>
|
yaml r <yaml file> <path>
|
||||||
```
|
```
|
||||||
|
|
||||||
### Basic
|
### Basic
|
||||||
@@ -21,7 +23,46 @@ b:
|
|||||||
```
|
```
|
||||||
then
|
then
|
||||||
```bash
|
```bash
|
||||||
yaml sample.yaml b.c
|
yaml r sample.yaml b.c
|
||||||
|
```
|
||||||
|
will output the value of '2'.
|
||||||
|
|
||||||
|
### Reading from STDIN
|
||||||
|
Given a sample.yaml file of:
|
||||||
|
```bash
|
||||||
|
cat sample.yaml | yaml r - b.c
|
||||||
|
```
|
||||||
|
will output the value of '2'.
|
||||||
|
|
||||||
|
### Splat
|
||||||
|
Given a sample.yaml file of:
|
||||||
|
```yaml
|
||||||
|
---
|
||||||
|
bob:
|
||||||
|
item1:
|
||||||
|
cats: bananas
|
||||||
|
item2:
|
||||||
|
cats: apples
|
||||||
|
```
|
||||||
|
then
|
||||||
|
```bash
|
||||||
|
yaml r sample.yaml bob.*.cats
|
||||||
|
```
|
||||||
|
will output
|
||||||
|
```yaml
|
||||||
|
- bananas
|
||||||
|
- apples
|
||||||
|
```
|
||||||
|
|
||||||
|
### Handling '.' in the yaml key
|
||||||
|
Given a sample.yaml file of:
|
||||||
|
```yaml
|
||||||
|
b.x:
|
||||||
|
c: 2
|
||||||
|
```
|
||||||
|
then
|
||||||
|
```bash
|
||||||
|
yaml r sample.yaml \"b.x\".c
|
||||||
```
|
```
|
||||||
will output the value of '2'.
|
will output the value of '2'.
|
||||||
|
|
||||||
@@ -38,10 +79,56 @@ b:
|
|||||||
```
|
```
|
||||||
then
|
then
|
||||||
```
|
```
|
||||||
yaml sample.yaml b.e.1.name
|
yaml r sample.yaml b.e[1].name
|
||||||
```
|
```
|
||||||
will output 'sam'
|
will output 'sam'
|
||||||
|
|
||||||
## TODO
|
### Array Splat
|
||||||
* Updating yaml files
|
e.g.: given a sample file of
|
||||||
* Handling '.' in path names
|
```yaml
|
||||||
|
b:
|
||||||
|
e:
|
||||||
|
- name: fred
|
||||||
|
value: 3
|
||||||
|
- name: sam
|
||||||
|
value: 4
|
||||||
|
```
|
||||||
|
then
|
||||||
|
```
|
||||||
|
yaml r sample.yaml b.e[*].name
|
||||||
|
```
|
||||||
|
will output:
|
||||||
|
```
|
||||||
|
- fred
|
||||||
|
- sam
|
||||||
|
```
|
||||||
|
|
||||||
|
## Update examples
|
||||||
|
|
||||||
|
### Update to stdout
|
||||||
|
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
|
||||||
|
```
|
||||||
|
|
||||||
|
### Updating yaml in-place
|
||||||
|
Given a sample.yaml file of:
|
||||||
|
```yaml
|
||||||
|
b:
|
||||||
|
c: 2
|
||||||
|
```
|
||||||
|
then
|
||||||
|
```bash
|
||||||
|
yaml w -i sample.yaml b.c cat
|
||||||
|
```
|
||||||
|
will update the sample.yaml file so that the value of 'c' is cat.
|
||||||
|
|||||||
83
data_navigator.go
Normal file
83
data_navigator.go
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
// "fmt"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
|
func write(context map[interface{}]interface{}, head string, tail []string, value interface{}) {
|
||||||
|
if len(tail) == 0 {
|
||||||
|
context[head] = value
|
||||||
|
} else {
|
||||||
|
// 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{} {
|
||||||
|
if head == "*" {
|
||||||
|
return readMapSplat(context, tail)
|
||||||
|
}
|
||||||
|
value := context[head]
|
||||||
|
return calculateValue(value, tail)
|
||||||
|
}
|
||||||
|
|
||||||
|
func readMapSplat(context map[interface{}]interface{}, tail []string) interface{} {
|
||||||
|
var newArray = make([]interface{}, len(context))
|
||||||
|
var i = 0
|
||||||
|
for _, value := range context {
|
||||||
|
if len(tail) > 0 {
|
||||||
|
newArray[i] = recurse(value, tail[0], tail[1:len(tail)])
|
||||||
|
} else {
|
||||||
|
newArray[i] = value
|
||||||
|
}
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
return newArray
|
||||||
|
}
|
||||||
|
|
||||||
|
func recurse(value interface{}, head string, tail []string) interface{} {
|
||||||
|
switch value.(type) {
|
||||||
|
case []interface{}:
|
||||||
|
if head == "*" {
|
||||||
|
return readArraySplat(value.([]interface{}), tail)
|
||||||
|
}
|
||||||
|
index, err := strconv.ParseInt(head, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
die("Error accessing array: %v", err)
|
||||||
|
}
|
||||||
|
return readArray(value.([]interface{}), index, tail)
|
||||||
|
case map[interface{}]interface{}:
|
||||||
|
return readMap(value.(map[interface{}]interface{}), head, tail)
|
||||||
|
default:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func readArray(array []interface{}, head int64, tail []string) interface{} {
|
||||||
|
if head > int64(len(array)) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
value := array[head]
|
||||||
|
|
||||||
|
return calculateValue(value, tail)
|
||||||
|
}
|
||||||
|
|
||||||
|
func readArraySplat(array []interface{}, tail []string) interface{} {
|
||||||
|
var newArray = make([]interface{}, len(array))
|
||||||
|
for index, value := range array {
|
||||||
|
newArray[index] = calculateValue(value, tail)
|
||||||
|
}
|
||||||
|
return newArray
|
||||||
|
}
|
||||||
|
|
||||||
|
func calculateValue(value interface{}, tail []string) interface{} {
|
||||||
|
if len(tail) > 0 {
|
||||||
|
return recurse(value, tail[0], tail[1:len(tail)])
|
||||||
|
}
|
||||||
|
return value
|
||||||
|
}
|
||||||
143
data_navigator_test.go
Normal file
143
data_navigator_test.go
Normal file
@@ -0,0 +1,143 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"gopkg.in/yaml.v2"
|
||||||
|
"os"
|
||||||
|
"sort"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func parseData(rawData string) map[interface{}]interface{} {
|
||||||
|
var parsedData map[interface{}]interface{}
|
||||||
|
err := yaml.Unmarshal([]byte(rawData), &parsedData)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println("Error parsing yaml: %v", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
return parsedData
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReadMap_simple(t *testing.T) {
|
||||||
|
var data = parseData(`
|
||||||
|
---
|
||||||
|
b:
|
||||||
|
c: 2
|
||||||
|
`)
|
||||||
|
assertResult(t, 2, readMap(data, "b", []string{"c"}))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReadMap_splat(t *testing.T) {
|
||||||
|
var data = parseData(`
|
||||||
|
---
|
||||||
|
mapSplat:
|
||||||
|
item1: things
|
||||||
|
item2: whatever
|
||||||
|
`)
|
||||||
|
assertResult(t, "[things whatever]", fmt.Sprintf("%v", readMap(data, "mapSplat", []string{"*"})))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReadMap_deep_splat(t *testing.T) {
|
||||||
|
var data = parseData(`
|
||||||
|
---
|
||||||
|
mapSplatDeep:
|
||||||
|
item1:
|
||||||
|
cats: bananas
|
||||||
|
item2:
|
||||||
|
cats: apples
|
||||||
|
`)
|
||||||
|
|
||||||
|
var result = readMap(data, "mapSplatDeep", []string{"*", "cats"}).([]interface{})
|
||||||
|
var actual = []string{result[0].(string), result[1].(string)}
|
||||||
|
sort.Strings(actual)
|
||||||
|
assertResult(t, "[apples bananas]", fmt.Sprintf("%v", actual))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReadMap_key_doesnt_exist(t *testing.T) {
|
||||||
|
var data = parseData(`
|
||||||
|
---
|
||||||
|
b:
|
||||||
|
c: 2
|
||||||
|
`)
|
||||||
|
assertResult(t, nil, readMap(data, "b.x.f", []string{"c"}))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReadMap_recurse_against_string(t *testing.T) {
|
||||||
|
var data = parseData(`
|
||||||
|
---
|
||||||
|
a: cat
|
||||||
|
`)
|
||||||
|
assertResult(t, nil, readMap(data, "a", []string{"b"}))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReadMap_with_array(t *testing.T) {
|
||||||
|
var data = parseData(`
|
||||||
|
---
|
||||||
|
b:
|
||||||
|
d:
|
||||||
|
- 3
|
||||||
|
- 4
|
||||||
|
`)
|
||||||
|
assertResult(t, 4, readMap(data, "b", []string{"d", "1"}))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReadMap_with_array_out_of_bounds(t *testing.T) {
|
||||||
|
var data = parseData(`
|
||||||
|
---
|
||||||
|
b:
|
||||||
|
d:
|
||||||
|
- 3
|
||||||
|
- 4
|
||||||
|
`)
|
||||||
|
assertResult(t, nil, readMap(data, "b", []string{"d", "3"}))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReadMap_with_array_splat(t *testing.T) {
|
||||||
|
var data = parseData(`
|
||||||
|
e:
|
||||||
|
-
|
||||||
|
name: Fred
|
||||||
|
thing: cat
|
||||||
|
-
|
||||||
|
name: Sam
|
||||||
|
thing: dog
|
||||||
|
`)
|
||||||
|
assertResult(t, "[Fred Sam]", fmt.Sprintf("%v", readMap(data, "e", []string{"*", "name"})))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWrite_simple(t *testing.T) {
|
||||||
|
var data = parseData(`
|
||||||
|
b:
|
||||||
|
c: 2
|
||||||
|
`)
|
||||||
|
|
||||||
|
write(data, "b", []string{"c"}, "4")
|
||||||
|
|
||||||
|
b := data["b"].(map[interface{}]interface{})
|
||||||
|
assertResult(t, "4", b["c"].(string))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWrite_with_no_tail(t *testing.T) {
|
||||||
|
var data = parseData(`
|
||||||
|
b:
|
||||||
|
c: 2
|
||||||
|
`)
|
||||||
|
write(data, "b", []string{}, "4")
|
||||||
|
|
||||||
|
b := data["b"]
|
||||||
|
assertResult(t, "4", fmt.Sprintf("%v", b))
|
||||||
|
}
|
||||||
|
|
||||||
|
func assertResult(t *testing.T, expectedValue interface{}, actualValue interface{}) {
|
||||||
|
if expectedValue != actualValue {
|
||||||
|
t.Error("Expected <", expectedValue, "> but got <", actualValue, ">", fmt.Sprintf("%T", actualValue))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func assertResultWithContext(t *testing.T, expectedValue interface{}, actualValue interface{}, context interface{}) {
|
||||||
|
|
||||||
|
if expectedValue != actualValue {
|
||||||
|
t.Error(context)
|
||||||
|
t.Error(": expected <", expectedValue, "> but got <", actualValue, ">")
|
||||||
|
}
|
||||||
|
}
|
||||||
55
path_parser.go
Normal file
55
path_parser.go
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
func parsePath(path string) []string {
|
||||||
|
return parsePathAccum([]string{}, path)
|
||||||
|
}
|
||||||
|
|
||||||
|
func parsePathAccum(paths []string, remaining string) []string {
|
||||||
|
head, tail := nextYamlPath(remaining)
|
||||||
|
if tail == "" {
|
||||||
|
return append(paths, head)
|
||||||
|
}
|
||||||
|
return parsePathAccum(append(paths, head), tail)
|
||||||
|
}
|
||||||
|
|
||||||
|
func nextYamlPath(path string) (pathElement string, remaining string) {
|
||||||
|
switch path[0] {
|
||||||
|
case '[':
|
||||||
|
// e.g [0].blah.cat -> we need to return "0" and "blah.cat"
|
||||||
|
return search(path[1:len(path)], []uint8{']'}, true)
|
||||||
|
case '"':
|
||||||
|
// e.g "a.b".blah.cat -> we need to return "a.b" and "blah.cat"
|
||||||
|
return search(path[1:len(path)], []uint8{'"'}, true)
|
||||||
|
default:
|
||||||
|
// e.g "a.blah.cat" -> return "a" and "blah.cat"
|
||||||
|
return search(path[0:len(path)], []uint8{'.', '['}, false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func search(path string, matchingChars []uint8, skipNext bool) (pathElement string, remaining string) {
|
||||||
|
for i := 0; i < len(path); i++ {
|
||||||
|
var char = path[i]
|
||||||
|
if contains(matchingChars, char) {
|
||||||
|
var remainingStart = i + 1
|
||||||
|
if skipNext {
|
||||||
|
remainingStart = remainingStart + 1
|
||||||
|
} else if !skipNext && char != '.' {
|
||||||
|
remainingStart = i
|
||||||
|
}
|
||||||
|
if remainingStart > len(path) {
|
||||||
|
remainingStart = len(path)
|
||||||
|
}
|
||||||
|
return path[0:i], path[remainingStart:len(path)]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return path, ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func contains(matchingChars []uint8, candidate uint8) bool {
|
||||||
|
for _, a := range matchingChars {
|
||||||
|
if a == candidate {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
42
path_parser_test.go
Normal file
42
path_parser_test.go
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
var parsePathsTests = []struct {
|
||||||
|
path string
|
||||||
|
expectedPaths []string
|
||||||
|
}{
|
||||||
|
{"a.b", []string{"a", "b"}},
|
||||||
|
{"a.b[0]", []string{"a", "b", "0"}},
|
||||||
|
}
|
||||||
|
|
||||||
|
func testParsePath(t *testing.T) {
|
||||||
|
for _, tt := range parsePathsTests {
|
||||||
|
assertResultWithContext(t, tt.expectedPaths, parsePath(tt.path), tt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var nextYamlPathTests = []struct {
|
||||||
|
path string
|
||||||
|
expectedElement string
|
||||||
|
expectedRemaining string
|
||||||
|
}{
|
||||||
|
{"a.b", "a", "b"},
|
||||||
|
{"a", "a", ""},
|
||||||
|
{"a.b.c", "a", "b.c"},
|
||||||
|
{"\"a.b\".c", "a.b", "c"},
|
||||||
|
{"a.\"b.c\".d", "a", "\"b.c\".d"},
|
||||||
|
{"[1].a.d", "1", "a.d"},
|
||||||
|
{"a[0].c", "a", "[0].c"},
|
||||||
|
{"[0]", "0", ""},
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNextYamlPath(t *testing.T) {
|
||||||
|
for _, tt := range nextYamlPathTests {
|
||||||
|
var element, remaining = nextYamlPath(tt.path)
|
||||||
|
assertResultWithContext(t, tt.expectedElement, element, tt)
|
||||||
|
assertResultWithContext(t, tt.expectedRemaining, remaining, tt)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,9 +5,13 @@ golint
|
|||||||
go test
|
go test
|
||||||
|
|
||||||
# acceptance test
|
# acceptance test
|
||||||
X=$(go run yaml.go sample.yaml b.c)
|
go build
|
||||||
|
X=$(./yaml r sample.yaml b.c)
|
||||||
|
|
||||||
if [ $X != 2 ]
|
if [ $X != 2 ]
|
||||||
then
|
then
|
||||||
echo "Failed acceptance test: expected 2 but was $X"
|
echo "Failed acceptance test: expected 2 but was $X"
|
||||||
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
go install
|
||||||
|
|||||||
@@ -1,4 +1,9 @@
|
|||||||
a: Easy! as one two three
|
a: Easy! as one two three
|
||||||
b:
|
b:
|
||||||
c: 3
|
c: things
|
||||||
d: [3, 4]
|
d: whatever
|
||||||
|
things:
|
||||||
|
thing1:
|
||||||
|
cat: 'fred'
|
||||||
|
thing2:
|
||||||
|
cat: 'sam'
|
||||||
|
|||||||
176
yaml.go
176
yaml.go
@@ -2,91 +2,157 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/codegangsta/cli"
|
"github.com/spf13/cobra"
|
||||||
"gopkg.in/yaml.v2"
|
"gopkg.in/yaml.v2"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"log"
|
|
||||||
"os"
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var trimOutput = true
|
||||||
|
var writeInplace = false
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
app := cli.NewApp()
|
var cmdRead = &cobra.Command{
|
||||||
app.Name = "yaml"
|
Use: "read [yaml_file] [path]",
|
||||||
app.Usage = "command line tool for reading and writing yaml"
|
Aliases: []string{"r"},
|
||||||
app.Commands = []cli.Command{
|
Short: "yaml r sample.yaml a.b.c",
|
||||||
{
|
Example: `
|
||||||
Name: "read",
|
yaml read things.yaml a.b.c
|
||||||
Aliases: []string{"r"},
|
yaml r - a.b.c (reads from stdin)
|
||||||
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",
|
yaml r things.yaml a.*.c
|
||||||
Action: readProperty,
|
yaml r things.yaml a.array[0].blah
|
||||||
},
|
yaml r things.yaml a.array[*].blah
|
||||||
|
`,
|
||||||
|
Long: "Outputs the value of the given path in the yaml file to STDOUT",
|
||||||
|
Run: readProperty,
|
||||||
}
|
}
|
||||||
app.Action = readProperty
|
|
||||||
app.Run(os.Args)
|
var cmdWrite = &cobra.Command{
|
||||||
|
Use: "write [yaml_file] [path] [value]",
|
||||||
|
Aliases: []string{"w"},
|
||||||
|
Short: "yaml w [--inplace/-i] sample.yaml a.b.c newValueForC",
|
||||||
|
Example: `
|
||||||
|
yaml write things.yaml a.b.c cat
|
||||||
|
yaml write --inplace things.yaml a.b.c cat
|
||||||
|
yaml w -i things.yaml a.b.c cat
|
||||||
|
`,
|
||||||
|
Long: `Updates the yaml file w.r.t the given path and value.
|
||||||
|
Outputs to STDOUT unless the inplace flag is used, in which case the file is updated instead.`,
|
||||||
|
Run: writeProperty,
|
||||||
|
}
|
||||||
|
cmdWrite.PersistentFlags().BoolVarP(&writeInplace, "inplace", "i", false, "update the yaml file inplace")
|
||||||
|
|
||||||
|
var rootCmd = &cobra.Command{Use: "yaml"}
|
||||||
|
rootCmd.PersistentFlags().BoolVarP(&trimOutput, "trim", "t", true, "trim yaml output")
|
||||||
|
rootCmd.AddCommand(cmdRead, cmdWrite)
|
||||||
|
rootCmd.Execute()
|
||||||
}
|
}
|
||||||
|
|
||||||
func readProperty(c *cli.Context) {
|
func readProperty(cmd *cobra.Command, args []string) {
|
||||||
var parsedData map[interface{}]interface{}
|
var parsedData map[interface{}]interface{}
|
||||||
readYaml(c, &parsedData)
|
|
||||||
|
|
||||||
var path = c.Args()[1]
|
readYaml(args, &parsedData)
|
||||||
var paths = strings.Split(path, ".")
|
|
||||||
|
|
||||||
fmt.Println(readMap(parsedData, paths[0], paths[1:len(paths)]))
|
if len(args) == 1 {
|
||||||
|
printYaml(parsedData)
|
||||||
|
os.Exit(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
var paths = parsePath(args[1])
|
||||||
|
|
||||||
|
printYaml(readMap(parsedData, paths[0], paths[1:len(paths)]))
|
||||||
}
|
}
|
||||||
|
|
||||||
func readYaml(c *cli.Context, parsedData *map[interface{}]interface{}) {
|
func writeProperty(cmd *cobra.Command, args []string) {
|
||||||
if len(c.Args()) == 0 {
|
if len(args) < 3 {
|
||||||
log.Fatalf("Must provide filename")
|
die("Must provide <filename> <path_to_update> <value>")
|
||||||
}
|
}
|
||||||
var rawData = readFile(c.Args()[0])
|
|
||||||
|
|
||||||
if len(c.Args()) == 1 {
|
var parsedData map[interface{}]interface{}
|
||||||
fmt.Println(string(rawData[:]))
|
readYaml(args, &parsedData)
|
||||||
os.Exit(0)
|
|
||||||
|
var paths = parsePath(args[1])
|
||||||
|
|
||||||
|
write(parsedData, paths[0], paths[1:len(paths)], getValue(args[2]))
|
||||||
|
|
||||||
|
if writeInplace {
|
||||||
|
ioutil.WriteFile(args[0], []byte(yamlToString(parsedData)), 0644)
|
||||||
|
} else {
|
||||||
|
printYaml(parsedData)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func getValue(argument string) interface{} {
|
||||||
|
var value, err interface{}
|
||||||
|
var inQuotes = argument[0] == '"'
|
||||||
|
if !inQuotes {
|
||||||
|
value, err = strconv.ParseFloat(argument, 64)
|
||||||
|
if err == nil {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
value, err = strconv.ParseBool(argument)
|
||||||
|
if err == nil {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
return argument
|
||||||
|
}
|
||||||
|
return argument[1 : len(argument)-1]
|
||||||
|
}
|
||||||
|
|
||||||
|
func printYaml(context interface{}) {
|
||||||
|
fmt.Println(yamlToString(context))
|
||||||
|
}
|
||||||
|
|
||||||
|
func yamlToString(context interface{}) string {
|
||||||
|
out, err := yaml.Marshal(context)
|
||||||
|
if err != nil {
|
||||||
|
die("error printing yaml: %v", err)
|
||||||
|
}
|
||||||
|
outStr := string(out)
|
||||||
|
// trim the trailing new line as it's easier for a script to add
|
||||||
|
// it in if required than to remove it
|
||||||
|
if trimOutput {
|
||||||
|
return strings.Trim(outStr, "\n ")
|
||||||
|
}
|
||||||
|
return outStr
|
||||||
|
}
|
||||||
|
|
||||||
|
func readYaml(args []string, parsedData *map[interface{}]interface{}) {
|
||||||
|
if len(args) == 0 {
|
||||||
|
die("Must provide filename")
|
||||||
|
}
|
||||||
|
|
||||||
|
var rawData []byte
|
||||||
|
if args[0] == "-" {
|
||||||
|
rawData = readStdin()
|
||||||
|
} else {
|
||||||
|
rawData = readFile(args[0])
|
||||||
}
|
}
|
||||||
|
|
||||||
err := yaml.Unmarshal([]byte(rawData), &parsedData)
|
err := yaml.Unmarshal([]byte(rawData), &parsedData)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("error: %v", err)
|
die("error: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func readStdin() []byte {
|
||||||
|
bytes, err := ioutil.ReadAll(os.Stdin)
|
||||||
|
if err != nil {
|
||||||
|
die("error reading stdin", err)
|
||||||
|
}
|
||||||
|
return bytes
|
||||||
|
}
|
||||||
|
|
||||||
func readFile(filename string) []byte {
|
func readFile(filename string) []byte {
|
||||||
var rawData, readError = ioutil.ReadFile(filename)
|
var rawData, readError = ioutil.ReadFile(filename)
|
||||||
if readError != nil {
|
if readError != nil {
|
||||||
log.Fatalf("error: %v", readError)
|
die("error: %v", readError)
|
||||||
}
|
}
|
||||||
return rawData
|
return rawData
|
||||||
}
|
}
|
||||||
|
|
||||||
func readMap(context map[interface{}]interface{}, head string, tail []string) interface{} {
|
func die(message ...interface{}) {
|
||||||
value := context[head]
|
fmt.Println(message)
|
||||||
if len(tail) > 0 {
|
os.Exit(1)
|
||||||
return recurse(value, tail[0], tail[1:len(tail)])
|
|
||||||
}
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
|
|
||||||
func recurse(value interface{}, head string, tail []string) interface{} {
|
|
||||||
switch value.(type) {
|
|
||||||
case []interface{}:
|
|
||||||
index, err := strconv.ParseInt(head, 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("Error accessing array: %v", err)
|
|
||||||
}
|
|
||||||
return readArray(value.([]interface{}), index, tail)
|
|
||||||
default:
|
|
||||||
return readMap(value.(map[interface{}]interface{}), head, tail)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func readArray(array []interface{}, head int64, tail []string) interface{} {
|
|
||||||
value := array[head]
|
|
||||||
if len(tail) > 0 {
|
|
||||||
return recurse(value, tail[0], tail[1:len(tail)])
|
|
||||||
}
|
|
||||||
return value
|
|
||||||
}
|
}
|
||||||
|
|||||||
43
yaml_test.go
43
yaml_test.go
@@ -1,41 +1,22 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"gopkg.in/yaml.v2"
|
|
||||||
"os"
|
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
var rawData = `
|
var getValueTests = []struct {
|
||||||
a: Easy!
|
argument string
|
||||||
b:
|
expectedResult interface{}
|
||||||
c: 2
|
testDescription string
|
||||||
d: [3, 4]
|
}{
|
||||||
`
|
{"true", true, "boolean"},
|
||||||
|
{"\"true\"", "true", "boolean as string"},
|
||||||
var parsedData map[interface{}]interface{}
|
{"3.4", 3.4, "number"},
|
||||||
|
{"\"3.4\"", "3.4", "number as string"},
|
||||||
func TestMain(m *testing.M) {
|
|
||||||
err := yaml.Unmarshal([]byte(rawData), &parsedData)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Println("Error parsing yaml: %v", err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
os.Exit(m.Run())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestReadMap_simple(t *testing.T) {
|
func TestGetValue(t *testing.T) {
|
||||||
result := readMap(parsedData, "b", []string{"c"})
|
for _, tt := range getValueTests {
|
||||||
if result != 2 {
|
assertResultWithContext(t, tt.expectedResult, getValue(tt.argument), tt.testDescription)
|
||||||
t.Error("Excpted 2 but got ", result)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestReadMap_array(t *testing.T) {
|
|
||||||
result := readMap(parsedData, "b", []string{"d", "1"})
|
|
||||||
if result != 4 {
|
|
||||||
t.Error("Excpted 4 but got ", result)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user