config: Unmarshal using default values

This commit is contained in:
Taylor Blau 2016-08-09 10:08:56 -06:00
parent 09f7d655fd
commit f0094ebd8f
2 changed files with 32 additions and 14 deletions

@ -124,8 +124,9 @@ func NewFrom(v Values) *Configuration {
// If an unknown environment is given, an error will be returned. If there is no
// method supporting conversion into a field's type, an error will be returned.
// If no value is associated with the given key and environment, the field will
// be left alone. If the field is already set to a non-zero value of that
// field's type, then it will be left alone.
// // only be modified if there is a config value present matching the given
// key. If the field is already set to a non-zero value of that field's type,
// then it will be left alone.
//
// Otherwise, the field will be set to the value of calling the
// appropriately-typed method on the specified environment.
@ -140,11 +141,6 @@ func (c *Configuration) Unmarshal(v interface{}) error {
field := into.Field(i)
sfield := into.Type().Field(i)
zero := reflect.Zero(field.Type())
if field.Interface() != zero.Interface() {
continue
}
key, env, err := c.parseTag(sfield.Tag)
if err != nil {
return err
@ -157,11 +153,16 @@ func (c *Configuration) Unmarshal(v interface{}) error {
var val interface{}
switch sfield.Type.Kind() {
case reflect.String:
val, _ = env.Get(key)
var ok bool
val, ok = env.Get(key)
if !ok {
val = field.String()
}
case reflect.Int:
val = env.Int(key, 0)
val = env.Int(key, int(field.Int()))
case reflect.Bool:
val = env.Bool(key, false)
val = env.Bool(key, field.Bool())
default:
return fmt.Errorf(
"lfs/config: unsupported target type for field %q: %v",

@ -604,7 +604,24 @@ func TestUnmarshalErrsOnNonPointerType(t *testing.T) {
assert.Equal(t, "lfs/config: unable to parse non-pointer type of config.T", err.Error())
}
func TestUnmarshalDoesNotOverrideNonZeroValues(t *testing.T) {
func TestUnmarshalLeavesNonZeroValuesWhenKeysEmpty(t *testing.T) {
v := &struct {
String string `git:"string"`
Int int `git:"int"`
Bool bool `git:"bool"`
}{"foo", 1, true}
cfg := NewFrom(Values{})
err := cfg.Unmarshal(v)
assert.Nil(t, err)
assert.Equal(t, "foo", v.String)
assert.Equal(t, 1, v.Int)
assert.Equal(t, true, v.Bool)
}
func TestUnmarshalOverridesNonZeroValuesWhenValuesPresent(t *testing.T) {
v := &struct {
String string `git:"string"`
Int int `git:"int"`
@ -622,9 +639,9 @@ func TestUnmarshalDoesNotOverrideNonZeroValues(t *testing.T) {
err := cfg.Unmarshal(v)
assert.Nil(t, err)
assert.Equal(t, "foo", v.String)
assert.Equal(t, 1, v.Int)
assert.Equal(t, true, v.Bool)
assert.Equal(t, "bar", v.String)
assert.Equal(t, 2, v.Int)
assert.Equal(t, false, v.Bool)
}
func TestUnmarshalDoesNotAllowBothOsAndGitTags(t *testing.T) {