From c436df805a554be6afe717c083659943ce25388c Mon Sep 17 00:00:00 2001 From: Reuben Miller Date: Sat, 18 May 2024 23:09:08 +0200 Subject: [PATCH 1/2] fix(data): return an error message when mixed data is provided --- pkg/jsonUtilities/shorthand.go | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/pkg/jsonUtilities/shorthand.go b/pkg/jsonUtilities/shorthand.go index 91cbd1a9b..485e9d765 100644 --- a/pkg/jsonUtilities/shorthand.go +++ b/pkg/jsonUtilities/shorthand.go @@ -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++ } @@ -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 @@ -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 } From 05cada6eadecd5e32dda117e26de19ab3192da69 Mon Sep 17 00:00:00 2001 From: Reuben Miller Date: Sat, 18 May 2024 23:14:14 +0200 Subject: [PATCH 2/2] add test to cover mixed data types --- tests/manual/common/flag_data.yaml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tests/manual/common/flag_data.yaml b/tests/manual/common/flag_data.yaml index 0c7ede427..ab254619b 100644 --- a/tests/manual/common/flag_data.yaml +++ b/tests/manual/common/flag_data.yaml @@ -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