Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(data): show error when --data mixes data types #372

Merged
merged 2 commits into from
May 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading