Can update arrays

This commit is contained in:
Mike Farah 2017-08-08 16:55:57 +10:00
parent 5bb0934710
commit 5514d2300b
2 changed files with 29 additions and 6 deletions

27
yaml.go
View File

@ -162,7 +162,7 @@ func newYaml(args []string) interface{} {
parsedData := make(yaml.MapSlice, 0) parsedData := make(yaml.MapSlice, 0)
return updateParsedData(parsedData, writeCommands) return updateParsedData(parsedData, writeCommands, "")
} }
func writeProperty(cmd *cobra.Command, args []string) { func writeProperty(cmd *cobra.Command, args []string) {
@ -177,18 +177,26 @@ func writeProperty(cmd *cobra.Command, args []string) {
} }
} }
func updateParsedData(parsedData yaml.MapSlice, writeCommands yaml.MapSlice) yaml.MapSlice { func updateParsedData(parsedData yaml.MapSlice, writeCommands yaml.MapSlice, prependCommand string) interface{} {
var prefix = ""
if prependCommand != "" {
prefix = prependCommand + "."
}
for _, entry := range writeCommands { for _, entry := range writeCommands {
path := entry.Key path := prefix + entry.Key.(string)
value := entry.Value value := entry.Value
var paths = parsePath(path.(string)) var paths = parsePath(path)
parsedData = writeMap(parsedData, paths, value) parsedData = writeMap(parsedData, paths, value)
} }
if prependCommand != "" {
return readMap(parsedData, prependCommand, make([]string, 0))
}
return parsedData return parsedData
} }
func updateYaml(args []string) interface{} { func updateYaml(args []string) interface{} {
var writeCommands yaml.MapSlice var writeCommands yaml.MapSlice
var prependCommand = ""
if writeScript != "" { if writeScript != "" {
readDataOrDie(writeScript, &writeCommands, false) readDataOrDie(writeScript, &writeCommands, false)
} else if len(args) < 3 { } else if len(args) < 3 {
@ -199,9 +207,16 @@ func updateYaml(args []string) interface{} {
} }
var parsedData yaml.MapSlice var parsedData yaml.MapSlice
readDataOrDie(args[0], &parsedData, inputJSON) err := readData(args[0], &parsedData, inputJSON)
if err != nil {
var generalData interface{}
readDataOrDie(args[0], &generalData, inputJSON)
item := yaml.MapItem{Key: "thing", Value: generalData}
parsedData = yaml.MapSlice{item}
prependCommand = "thing"
}
return updateParsedData(parsedData, writeCommands) return updateParsedData(parsedData, writeCommands, prependCommand)
} }
func parseValue(argument string) interface{} { func parseValue(argument string) interface{} {

View File

@ -63,6 +63,14 @@ func TestUpdateYaml(t *testing.T) {
formattedResult) formattedResult)
} }
func TestUpdateYamlArray(t *testing.T) {
result := updateYaml([]string{"sample_array.yaml", "[0]", "3"})
formattedResult := fmt.Sprintf("%v", result)
assertResult(t,
"[3 2 3]",
formattedResult)
}
func TestUpdateYaml_WithScript(t *testing.T) { func TestUpdateYaml_WithScript(t *testing.T) {
writeScript = "instruction_sample.yaml" writeScript = "instruction_sample.yaml"
updateYaml([]string{"sample.yaml"}) updateYaml([]string{"sample.yaml"})