Validate string slice fields
This commit is contained in:
parent
0cf8876f8a
commit
41a841c83d
@ -45,6 +45,13 @@ func OptionFromString(entries ...string) (*Option, error) {
|
|||||||
return option_from_string(map[string]string{}, entries...)
|
return option_from_string(map[string]string{}, entries...)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func is_string_slice(f reflect.Value) bool {
|
||||||
|
if f.Kind() != reflect.Slice {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return f.Type().Elem().Kind() == reflect.String
|
||||||
|
}
|
||||||
|
|
||||||
func OptionsFromStruct(pointer_to_options_struct interface{}) ([]*Option, error) {
|
func OptionsFromStruct(pointer_to_options_struct interface{}) ([]*Option, error) {
|
||||||
val := reflect.ValueOf(pointer_to_options_struct).Elem()
|
val := reflect.ValueOf(pointer_to_options_struct).Elem()
|
||||||
if val.Kind() != reflect.Struct {
|
if val.Kind() != reflect.Struct {
|
||||||
@ -61,6 +68,9 @@ func OptionsFromStruct(pointer_to_options_struct interface{}) ([]*Option, error)
|
|||||||
typ := "str"
|
typ := "str"
|
||||||
switch f.Kind() {
|
switch f.Kind() {
|
||||||
case reflect.Slice:
|
case reflect.Slice:
|
||||||
|
if !is_string_slice(f) {
|
||||||
|
return nil, fmt.Errorf("The field %s is not a slice of strings", field_name)
|
||||||
|
}
|
||||||
typ = "list"
|
typ = "list"
|
||||||
case reflect.Int:
|
case reflect.Int:
|
||||||
typ = "int"
|
typ = "int"
|
||||||
|
|||||||
@ -6,7 +6,6 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"reflect"
|
"reflect"
|
||||||
"regexp"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
@ -425,8 +424,8 @@ func (self *Command) GetOptionValues(pointer_to_options_struct interface{}) erro
|
|||||||
f.SetBool(v)
|
f.SetBool(v)
|
||||||
case StringOption:
|
case StringOption:
|
||||||
if opt.IsList {
|
if opt.IsList {
|
||||||
if f.Kind() != reflect.Slice {
|
if !is_string_slice(f) {
|
||||||
return fmt.Errorf("The field: %s must be a slice", field_name)
|
return fmt.Errorf("The field: %s must be a []string", field_name)
|
||||||
}
|
}
|
||||||
v := opt.parsed_value().([]string)
|
v := opt.parsed_value().([]string)
|
||||||
f.Set(reflect.ValueOf(v))
|
f.Set(reflect.ValueOf(v))
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user