Skip to content

Commit

Permalink
up: structs - update the tag value parse func, allow limit keys
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Sep 27, 2022
1 parent ae3ee9f commit 4e6e065
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 3 deletions.
2 changes: 1 addition & 1 deletion envutil/envutil_test.go
Expand Up @@ -50,7 +50,7 @@ func TestParseEnvValue(t *testing.T) {
}, func() {
is.Eq("abc", Getenv("FirstEnv"))
is.Eq("def", Getenv("SecondEnv"))
is.Eq("abc/def", ParseEnvValue(rVal))
is.Eq("abc/def", ParseValue(rVal))
is.Eq("abc string", VarReplace("${FirstEnv} string"))
})

Expand Down
11 changes: 9 additions & 2 deletions structs/tags.go
Expand Up @@ -6,6 +6,7 @@ import (
"reflect"
"strings"

"github.com/gookit/goutil/arrutil"
"github.com/gookit/goutil/maputil"
"github.com/gookit/goutil/strutil"
)
Expand Down Expand Up @@ -208,7 +209,9 @@ func ParseTagValueDefault(field, tagVal string) (mp maputil.SMap, err error) {
// Examples:
//
// eg: "desc;required;default;shorts"
// type My
// type MyStruct {
// Age int `flag:"int option message;;a,b"`
// }
// sepStr := ";"
// defines := []string{"desc", "required", "default", "shorts"}
func ParseTagValueDefine(sep string, defines []string) TagValFunc {
Expand All @@ -233,7 +236,7 @@ func ParseTagValueDefine(sep string, defines []string) TagValFunc {
// ParseTagValueNamed parse k-v tag value string. it's like INI format contents.
//
// eg: "name=int0;shorts=i;required=true;desc=int option message"
func ParseTagValueNamed(field, tagVal string) (mp maputil.SMap, err error) {
func ParseTagValueNamed(field, tagVal string, keys ...string) (mp maputil.SMap, err error) {
ss := strutil.Split(tagVal, ";")
ln := len(ss)
if ln == 0 {
Expand All @@ -249,6 +252,10 @@ func ParseTagValueNamed(field, tagVal string) (mp maputil.SMap, err error) {

kvNodes := strings.SplitN(s, "=", 2)
key, val := kvNodes[0], strings.TrimSpace(kvNodes[1])
if len(keys) > 0 && !arrutil.StringsHas(keys, key) {
err = fmt.Errorf("parse tag error on field '%s': invalid key name '%s'", field, key)
return
}

mp[key] = val
}
Expand Down
3 changes: 3 additions & 0 deletions structs/tags_test.go
Expand Up @@ -212,4 +212,7 @@ func TestParseTagValueNamed(t *testing.T) {
assert.NoErr(t, err)
assert.NotEmpty(t, mp)
assert.Eq(t, "inhere", mp.Str("default"))

mp, err = structs.ParseTagValueNamed("name", "name=n;default=inhere", "name")
assert.ErrSubMsg(t, err, "parse tag error on field 'name'")
}

0 comments on commit 4e6e065

Please sign in to comment.