diff --git a/pkg/cmd/api/fields.go b/pkg/cmd/api/fields.go index c9048a648..024eb12ca 100644 --- a/pkg/cmd/api/fields.go +++ b/pkg/cmd/api/fields.go @@ -99,6 +99,9 @@ func parseFields(opts *ApiOptions) (map[string]interface{}, error) { } } } else { + if _, exists := destMap[subkey]; exists { + return fmt.Errorf("unexpected override existing field under %q", subkey) + } destMap[subkey] = value } return nil diff --git a/pkg/cmd/api/fields_test.go b/pkg/cmd/api/fields_test.go index 49bda927d..73bc7463c 100644 --- a/pkg/cmd/api/fields_test.go +++ b/pkg/cmd/api/fields_test.go @@ -11,6 +11,7 @@ import ( "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/iostreams" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_parseFields(t *testing.T) { @@ -135,6 +136,91 @@ func Test_parseFields_nested(t *testing.T) { `), "\n"), string(jsonData)) } +func Test_parseFields_errors(t *testing.T) { + ios, stdin, _, _ := iostreams.Test() + fmt.Fprint(stdin, "pasted contents") + + tests := []struct { + name string + opts *ApiOptions + expected string + }{ + { + name: "cannot overwrite string to array", + opts: &ApiOptions{ + IO: ios, + RawFields: []string{ + "object[field]=A", + "object[field][]=this should be an error", + }, + }, + expected: `expected array type under "field", got string`, + }, + { + name: "cannot overwrite string to object", + opts: &ApiOptions{ + IO: ios, + RawFields: []string{ + "object[field]=B", + "object[field][field2]=this should be an error", + }, + }, + expected: `expected map type under "field", got string`, + }, + { + name: "cannot overwrite object to string", + opts: &ApiOptions{ + IO: ios, + RawFields: []string{ + "object[field][field2]=C", + "object[field]=this should be an error", + }, + }, + expected: `unexpected override existing field under "field"`, + }, + { + name: "cannot overwrite object to array", + opts: &ApiOptions{ + IO: ios, + RawFields: []string{ + "object[field][field2]=D", + "object[field][]=this should be an error", + }, + }, + expected: `expected array type under "field", got map[string]interface {}`, + }, + { + name: "cannot overwrite array to string", + opts: &ApiOptions{ + IO: ios, + RawFields: []string{ + "object[field][]=E", + "object[field]=this should be an error", + }, + }, + expected: `unexpected override existing field under "field"`, + }, + { + name: "cannot overwrite array to object", + opts: &ApiOptions{ + IO: ios, + RawFields: []string{ + "object[field][]=F", + "object[field][field2]=this should be an error", + }, + }, + expected: `expected map type under "field", got []interface {}`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := parseFields(tt.opts) + require.EqualError(t, err, tt.expected) + }) + } +} + func Test_magicFieldValue(t *testing.T) { f, err := os.CreateTemp(t.TempDir(), "gh-test") if err != nil {