Refactoring write command to allow splat

This commit is contained in:
Mike Farah 2019-05-01 08:40:35 +10:00
parent 2dbde6b9fb
commit cda9a82906
3 changed files with 20 additions and 13 deletions

View File

@ -775,7 +775,7 @@ func TestWriteCmd_AppendEmptyArray(t *testing.T) {
defer removeTempYamlFile(filename)
cmd := getRootCommand()
result := runCmd(cmd, fmt.Sprintf("write %s b[+] v", filename))
result := runCmd(cmd, fmt.Sprintf("write -v %s b[+] v", filename))
if result.Error != nil {
t.Error(result.Error)
}

View File

@ -2,6 +2,7 @@ package main
import (
"fmt"
"reflect"
"strconv"
yaml "gopkg.in/mikefarah/yaml.v2"
@ -41,7 +42,7 @@ func getArray(context interface{}) (array []interface{}, ok bool) {
}
func writeMap(context interface{}, paths []string, value interface{}) yaml.MapSlice {
log.Debugf("writeMap for %v for %v with value %v\n", paths, context, value)
log.Debugf("writeMap with path %v for %v to set value %v\n", paths, context, value)
mapSlice := getMapSlice(context)
@ -69,19 +70,25 @@ func updatedChildValue(child interface{}, remainingPaths []string, value interfa
if len(remainingPaths) == 0 {
return value
}
log.Debugf("updatedChildValue for child %v with path %v to set value %v", child, remainingPaths, value)
log.Debugf("type of child is %v", reflect.TypeOf(child))
_, nextIndexErr := strconv.ParseInt(remainingPaths[0], 10, 64)
if nextIndexErr != nil && remainingPaths[0] != "+" {
// must be a map
return writeMap(child, remainingPaths, value)
}
// must be an array
switch child := child.(type) {
case nil:
if nextIndexErr == nil || remainingPaths[0] == "+" { // || remainingPaths[0] == "*"
return writeArray(child, remainingPaths, value)
}
case []interface{}:
if nextIndexErr == nil || remainingPaths[0] == "+" { // || remainingPaths[0] == "*"
return writeArray(child, remainingPaths, value)
}
}
return writeMap(child, remainingPaths, value)
}
func writeArray(context interface{}, paths []string, value interface{}) []interface{} {
log.Debugf("writeArray for %v for %v with value %v\n", paths, context, value)
log.Debugf("writeArray with path %v for %v to set value %v\n", paths, context, value)
array, _ := getArray(context)
if len(paths) == 0 {

View File

@ -253,11 +253,11 @@ b:
func TestWrite_new_array_deep(t *testing.T) {
var data = parseData(`
b:
c: 2
a: apple
`)
var expected = `b:
var expected = `a: apple
b:
- c: "4"`
updated := writeMap(data, []string{"b", "0", "c"}, "4")