Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(cobra): add cobra bind support #4

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion bind.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ import (
"strings"
"time"

"github.com/spf13/cobra"
"github.com/spf13/pflag"
)

Expand Down Expand Up @@ -289,6 +290,19 @@ func Bind(fs FlagSet, v interface{}, opts ...Option) error {
return newBind(opts...).bind(fs, v)
}

func BindCobra(cmd *cobra.Command, v interface{}, opts ...Option) (err error) {
if err = newBind(append(opts, CobraFilter("persistent"))...).bind(cmd.PersistentFlags(), v); err != nil {
return err
}
if err = newBind(append(opts, CobraFilter("local"))...).bind(cmd.LocalFlags(), v); err != nil {
return err
}
if err = newBind(append(opts, CobraFilter("flags"))...).bind(cmd.Flags(), v); err != nil {
return err
}
return nil
}

func (b bind) bind(fs FlagSet, v interface{}) (err error) {

// Hand control over to the Binder implementation.
Expand Down Expand Up @@ -353,7 +367,7 @@ func (b bind) bind(fs FlagSet, v interface{}) (err error) {
tagStr, hasTag := structField.Tag.Lookup("flag")
tag := newFlagTag(tagStr)

if tag.IsIgnored {
if b.IsIgnored(tag) {
continue
}

Expand Down Expand Up @@ -590,6 +604,7 @@ func bindPFlag(fs PFlagSet, tag flagTag, p interface{}, typeName string) bool {
// If not, use the pflagValue shim...
pp = pflagValue{p, typeName}
}

f = fs.VarPF(pp, tag.Name, tag.ShortName, tag.Usage)
case *json.RawMessage:
f = fs.VarPF((*JSONRawMessage)(p), tag.Name, tag.ShortName, tag.Usage)
Expand Down
53 changes: 52 additions & 1 deletion bind_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import (
"testing"
"time"

"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -112,7 +113,7 @@ func (test *BindTest) test(t *testing.T) {
for _, use := range test.UsageContains {
assert.Contains(usage, use, "flag.FlagSet.Usage()")
}
//fmt.Println(usage)
// fmt.Println(usage)
if test.UsePFlag {
for _, use := range test.UsageNotContains {
assert.NotContains(usage, use, "flag.FlagSet.Usage()")
Expand Down Expand Up @@ -239,6 +240,56 @@ func TestBind(t *testing.T) {
}
}

type ValidCobraFlagConfig struct {
StringVar string `flag:"string-var,s;default value;my usage;persistent;"`
}

func TestBindCobra(t *testing.T) {
tt := []struct {
name string
F interface{}
FName string
FCobraSet string
FWant interface{}
Err error
}{
{
name: "with persistent flags",
F: &ValidCobraFlagConfig{},
FName: "string-var",
FCobraSet: "persistent",
FWant: "default value",
Err: nil,
},
}

for _, tt := range tt {
t.Run(tt.name, func(t *testing.T) {
cmd := &cobra.Command{}
err := BindCobra(cmd, tt.F)
if tt.Err != nil {
assert.Equal(t, tt.Err, err)
}

var fs *pflag.FlagSet
switch tt.FCobraSet {
case "persistent":
fs = cmd.PersistentFlags()
case "local":
fs = cmd.LocalFlags()
case "flags":
fs = cmd.Flags()
default:
panic("unsupported cobra FlagSet")
}

got := fs.Lookup(tt.FName)
assert.NotNil(t, got)
assert.Equal(t, fmt.Sprintf("%v", tt.FWant), got.Value.String())
})
}
}

var tests = []BindTest{
{
Name: "ErrorInvalidType_bool",
Expand Down
16 changes: 15 additions & 1 deletion flagtag.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@ type flagTag struct {

// Nested struct
Flatten bool // `flag:";;;flatten"`

// Nested struct
Persistent bool // `flag:";;;persistent"`
Local bool // `flag:";;;local"`
Flags bool // `flag:";;;flags"`
}

// newFlagTag parses all possible tag settings.
Expand Down Expand Up @@ -115,5 +120,14 @@ func (fTag *flagTag) parseOptions(opts string) {
opts = strings.ToLower(opts)
fTag.Hidden = strings.Contains(opts, "hidden")
fTag.HideDefault = strings.Contains(opts, "hide-default")
fTag.Flatten = strings.Contains(opts, "flatten")
switch {
case strings.Contains(opts, "persistent"):
fTag.Persistent = true
case strings.Contains(opts, "local"):
fTag.Local = true
case strings.Contains(opts, "flags"):
fallthrough
default:
fTag.Flags = true
}
}
3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ module github.com/AdamSLevy/flagbind
go 1.14

require (
github.com/spf13/cobra v1.3.0
github.com/spf13/pflag v1.0.5
github.com/stretchr/testify v1.5.1
github.com/stretchr/testify v1.7.0
)
Loading