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

pkg/types: return error instead of crashing when code supplies an incompatible type to types.LoadArgs() #460

Merged
merged 2 commits into from
Jul 5, 2017
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
15 changes: 13 additions & 2 deletions pkg/types/args.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,12 @@ func GetKeyField(keyString string, v reflect.Value) reflect.Value {
return v.Elem().FieldByName(keyString)
}

// UnmarshalableArgsError is used to indicate error unmarshalling args
// from the args-string in the form "K=V;K2=V2;..."
type UnmarshalableArgsError struct {
error
}

// LoadArgs parses args from a string in the form "K=V;K2=V2;..."
func LoadArgs(args string, container interface{}) error {
if args == "" {
Expand All @@ -85,8 +91,13 @@ func LoadArgs(args string, container interface{}) error {
unknownArgs = append(unknownArgs, pair)
continue
}

u := keyField.Addr().Interface().(encoding.TextUnmarshaler)
keyFieldIface := keyField.Addr().Interface()
u, ok := keyFieldIface.(encoding.TextUnmarshaler)
if !ok {
return UnmarshalableArgsError{fmt.Errorf(
"ARGS: cannot unmarshal into field '%s' - type '%s' does not implement encoding.TextUnmarshaler",
keyString, reflect.TypeOf(keyFieldIface))}
}
err := u.UnmarshalText([]byte(valueString))
if err != nil {
return fmt.Errorf("ARGS: error parsing value of pair %q: %v)", pair, err)
Expand Down
11 changes: 11 additions & 0 deletions pkg/types/args_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,4 +118,15 @@ var _ = Describe("LoadArgs", func() {
Expect(err).NotTo(HaveOccurred())
})
})

Context("When known arguments are passed and cannot be unmarshalled", func() {
It("LoadArgs should fail", func() {
conf := struct {
IP IPNet
}{}
err := LoadArgs("IP=10.0.0.0/24", &conf)
Expect(err).To(HaveOccurred())

})
})
})