Skip to content

Commit

Permalink
fix: must provide ptr for call FromStruct
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Oct 11, 2021
1 parent a76759b commit 1cea878
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 4 deletions.
19 changes: 15 additions & 4 deletions gflag.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,13 +116,18 @@ func NewFlags(nameWithDesc ...string) *Flags {
}

var flagValueType = reflect.TypeOf(new(flag.Value)).Elem()
var errNotAnStruct = errors.New("must input an struct")
var errNotPtrValue = errors.New("must provide an ptr value")
var errNotAnStruct = errors.New("must provide an struct ptr")
var errTagRuleType = errors.New("invalid tag rule type on struct")

// FromStruct from struct tag binding options
func (fs *Flags) FromStruct(s interface{}) error {
v := reflect.ValueOf(s)
if v.Kind() == reflect.Ptr && !v.IsNil() {
func (fs *Flags) FromStruct(ptr interface{}) error {
v := reflect.ValueOf(ptr)
if v.Kind() != reflect.Ptr {
return errNotPtrValue
}

if !v.IsNil() {
v = v.Elem()
}

Expand Down Expand Up @@ -240,6 +245,12 @@ func (fs *Flags) SetOptions(opt *FlagsOption) {
fs.opt = opt
}

// UseSimpleRule for the parse tag value rule string. see TagRuleSimple
func (fs *Flags) UseSimpleRule() *Flags {
fs.opt.TagRuleType = TagRuleSimple
return fs
}

// WithOptions for the object.
func (fs *Flags) WithOptions(fns func(opt *FlagsOption)) *Flags {
fns(fs.opt)
Expand Down
24 changes: 24 additions & 0 deletions gflag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,11 @@ func TestFlags_FromStruct_simple(t *testing.T) {

assert.Equal(t, 13, opt.Int)
assert.Equal(t, "xyz", opt.Str)

// not use ptr
opts1 := userOpts0{}
err = fs.FromStruct(opts1)
assert.Error(t, err)
}

func TestFlags_FromStruct_ptrField(t *testing.T) {
Expand Down Expand Up @@ -417,6 +422,25 @@ func TestFlags_FromStruct_ptrField(t *testing.T) {
fs.PrintHelpPanel()
}

func TestFlags_FromStruct_noNameStruct(t *testing.T) {
logOpts := struct {
Abbrev bool `flag:"Only display the abbrev commit ID"`
NoColor bool `flag:"Dont use color render git output"`
MaxCommit int `flag:"Max display how many commits;;15"`
Logfile string `flag:"export changelog message to file"`
Exclude gcli.String `flag:"exclude contains given sub-string. multi by comma split."`
}{}

fs := gcli.NewFlags("test")
fs.UseSimpleRule()
// err := fs.FromStruct(logOpts)
err := fs.FromStruct(&logOpts)

assert.NoError(t, err)
assert.True(t, fs.HasFlag("abbrev"))
assert.True(t, fs.HasFlagMeta("abbrev"))
}

func TestFlags_FromStruct(t *testing.T) {
type userOpts struct {
Int int `flag:"name=int0;shorts=i;required=true;desc=int option message"`
Expand Down

0 comments on commit 1cea878

Please sign in to comment.