Generic options model

Signed-off-by: Arnaud Porterie <arnaud.porterie@docker.com>
This commit is contained in:
Arnaud Porterie
2015-02-19 22:44:51 -08:00
parent feab850ade
commit 35bf4109dc
6 changed files with 183 additions and 23 deletions
+47
View File
@@ -0,0 +1,47 @@
// The options package provides a way to pass unstructured sets of options to a
// component expecting a strongly-typed configuration structure.
package options
import (
"fmt"
"reflect"
)
type NoSuchFieldError struct {
Field string
Type string
}
func (e NoSuchFieldError) Error() string {
return fmt.Sprintf("no field %q in type %q", e.Field, e.Type)
}
type CannotSetFieldError struct {
Field string
Type string
}
func (e CannotSetFieldError) Error() string {
return fmt.Sprintf("cannot set field %q of type %q", e.Field, e.Type)
}
type Generic map[string]interface{}
func NewGeneric() Generic {
return make(Generic)
}
func GenerateFromModel(options Generic, model interface{}) (interface{}, error) {
res := reflect.New(reflect.TypeOf(model))
for name, value := range options {
field := res.Elem().FieldByName(name)
if !field.IsValid() {
return nil, NoSuchFieldError{name, reflect.TypeOf(model).Name()}
}
if !field.CanSet() {
return nil, CannotSetFieldError{name, reflect.TypeOf(model).Name()}
}
field.Set(reflect.ValueOf(value))
}
return res.Interface(), nil
}
+57
View File
@@ -0,0 +1,57 @@
package options
import (
"reflect"
"testing"
)
func TestGenerate(t *testing.T) {
gen := NewGeneric()
gen["Int"] = 1
gen["Rune"] = 'b'
gen["Float64"] = 2.0
type Model struct {
Int int
Rune rune
Float64 float64
}
result, err := GenerateFromModel(gen, Model{})
if err != nil {
t.Fatal(err)
}
cast, ok := result.(*Model)
if !ok {
t.Fatalf("result has unexpected type %s", reflect.TypeOf(result))
}
if expected := 1; cast.Int != expected {
t.Fatalf("wrong value for field Int: expected %v, got %v", expected, cast.Int)
}
if expected := 'b'; cast.Rune != expected {
t.Fatalf("wrong value for field Rune: expected %v, got %v", expected, cast.Rune)
}
if expected := 2.0; cast.Float64 != expected {
t.Fatalf("wrong value for field Int: expected %v, got %v", expected, cast.Float64)
}
}
func TestGenerateMissingField(t *testing.T) {
type Model struct{}
_, err := GenerateFromModel(Generic{"foo": "bar"}, Model{})
if _, ok := err.(NoSuchFieldError); !ok {
t.Fatalf("expected NoSuchFieldError, got %#v", err)
}
}
func TestFieldCannotBeSet(t *testing.T) {
type Model struct{ foo int }
_, err := GenerateFromModel(Generic{"foo": "bar"}, Model{})
if _, ok := err.(CannotSetFieldError); !ok {
t.Fatalf("expected CannotSetFieldError, got %#v", err)
}
}