Skip to content

Commit

Permalink
"options" tag now can set target value in the config (#452)
Browse files Browse the repository at this point in the history
* Parameter tag can now set target value
  • Loading branch information
vadimalekseev authored Aug 10, 2023
1 parent 9039ac3 commit 3324c3d
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
16 changes: 15 additions & 1 deletion cfg/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -362,17 +362,31 @@ func ParseField(v reflect.Value, vField reflect.Value, tField *reflect.StructFie
return fmt.Errorf("options deals with strings only, but field %s has %s type", tField.Name, tField.Type.Name())
}

idx := -1
found := false
for _, part := range parts {
for i, part := range parts {
if vField.String() == part {
found = true
idx = i
break
}
}

if !found {
return fmt.Errorf("field %s should be one of %s, got=%s", tField.Name, tag, vField.String())
}

finalField := v.FieldByName(tField.Name + "_")
if finalField != (reflect.Value{}) {
switch finalField.Kind() {
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
finalField.SetInt(int64(idx))
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
finalField.SetUint(uint64(idx))
default:
return fmt.Errorf("final field must be an integer")
}
}
}

tag = tField.Tag.Get("parse")
Expand Down
20 changes: 17 additions & 3 deletions cfg/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,16 @@ type strDefault struct {
T string `default:"sync"`
}

type PersistenceMode byte

const (
PersistenceModeAsync PersistenceMode = iota
PersistenceModeSync
)

type strOptions struct {
T string `default:"async" options:"async|sync"`
T string `default:"async" options:"async|sync"`
T_ PersistenceMode
}

type strExpression struct {
Expand Down Expand Up @@ -122,17 +130,23 @@ func TestParseDuration(t *testing.T) {
}

func TestParseOptionsOk(t *testing.T) {
a := assert.New(t)

s := &strOptions{T: "async"}
err := Parse(s, nil)
a.NoError(Parse(s, nil))
a.Equal(s.T_, PersistenceModeAsync)

assert.NoError(t, err, "shouldn't be an error")
s.T = "sync"
a.NoError(Parse(s, nil))
a.Equal(s.T_, PersistenceModeSync)
}

func TestParseOptionsErr(t *testing.T) {
s := &strOptions{T: "sequential"}
err := Parse(s, nil)

assert.NotNil(t, err, "should be an error")
assert.Equal(t, PersistenceMode(0), s.T_)
}

func TestParseExpressionMul(t *testing.T) {
Expand Down

0 comments on commit 3324c3d

Please sign in to comment.