Skip to content

Commit

Permalink
Merge pull request #372 from reubenmiller/fix-mixed-shorthand-json
Browse files Browse the repository at this point in the history
fix(data): show error when --data mixes data types
  • Loading branch information
reubenmiller committed May 18, 2024
2 parents f6641dc + 05cada6 commit b5fa65c
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
20 changes: 17 additions & 3 deletions pkg/jsonUtilities/shorthand.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,9 @@ func parseShorthandJSONStructure(value string, data map[string]interface{}) erro

for i := 0; i < len(outputValues); i += 2 {
key := strings.Trim(outputValues[i], " ")
setValue(data, key, parseValue(outputValues[i+1]))
if setErr := setValue(data, key, parseValue(outputValues[i+1])); setErr != nil {
return setErr
}
// data[key] = parseValue(outputValues[i+1])
validItems++
}
Expand All @@ -201,7 +203,7 @@ func parseShorthandJSONStructure(value string, data map[string]interface{}) erro
return nil
}

func setValue(data map[string]interface{}, path string, value interface{}) {
func setValue(data map[string]interface{}, path string, value interface{}) error {
keys := strings.Split(path, Separator)
currentMap := data

Expand All @@ -213,10 +215,22 @@ func setValue(data map[string]interface{}, path string, value interface{}) {
if _, ok := currentMap[key]; !ok {
currentMap[key] = make(map[string]interface{})
}
currentMap = currentMap[key].(map[string]interface{})
// check if type is as exampled
if cm, ok := currentMap[key].(map[string]interface{}); ok {
currentMap = cm
} else {
// throw an error if users are trying to write an object
// to an existing non-object field (e.g. string/float etc.)
return fmt.Errorf(
"mixed types detected. trying to assign an object to a %T. path=%s",
currentMap[key],
strings.Join(keys[0:i+1], Separator),
)
}
} else {
currentMap[key] = value
}
}
}
return nil
}
8 changes: 8 additions & 0 deletions tests/manual/common/flag_data.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,11 @@ tests:
"subtypes": ["linuxA", "linuxB"]
}
}
It should not panic when mixing data types:
command: |
c8y devices create -n --data one=1 --data one.two=null --dry
exit-code: 101
stderr:
not-contains:
- panic

0 comments on commit b5fa65c

Please sign in to comment.