Add BindTo option for binding interface implementations.
This commit is contained in:
+10
@@ -126,6 +126,16 @@ func Bind(args ...interface{}) OptionFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// BindTo allows binding of implementations to interfaces.
|
||||
//
|
||||
// BindTo(impl, (*iface)(nil))
|
||||
func BindTo(impl, iface interface{}) OptionFunc {
|
||||
return func(k *Kong) error {
|
||||
k.bindings[reflect.TypeOf(iface).Elem()] = reflect.ValueOf(impl)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Help printer to use.
|
||||
func Help(help HelpPrinter) OptionFunc {
|
||||
return func(k *Kong) error {
|
||||
|
||||
+29
-5
@@ -1,19 +1,18 @@
|
||||
package kong_test
|
||||
package kong
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/alecthomas/kong"
|
||||
)
|
||||
|
||||
func TestOptions(t *testing.T) {
|
||||
var cli struct{}
|
||||
p, err := kong.New(&cli, kong.Name("name"), kong.Description("description"), kong.Writers(nil, nil), kong.Exit(nil))
|
||||
p, err := New(&cli, Name("name"), Description("description"), Writers(nil, nil), Exit(nil))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "name", p.Model.Name)
|
||||
require.Equal(t, "description", p.Model.Help)
|
||||
@@ -44,8 +43,33 @@ func TestConfigLoading(t *testing.T) {
|
||||
err = json.NewEncoder(second).Encode(&cli)
|
||||
require.NoError(t, err)
|
||||
|
||||
p := mustNew(t, &cli, kong.Configuration(kong.JSON, first.Name(), second.Name()))
|
||||
p, err := New(&cli, Configuration(JSON, first.Name(), second.Name()))
|
||||
require.NoError(t, err)
|
||||
_, err = p.Parse(nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "first", cli.Flag)
|
||||
}
|
||||
|
||||
type impl string
|
||||
|
||||
func (impl) Method() {}
|
||||
|
||||
func TestBindTo(t *testing.T) {
|
||||
type iface interface {
|
||||
Method()
|
||||
}
|
||||
|
||||
saw := ""
|
||||
method := func(i iface) error { // nolint: unparam
|
||||
saw = string(i.(impl))
|
||||
return nil
|
||||
}
|
||||
|
||||
var cli struct{}
|
||||
|
||||
p, err := New(&cli, BindTo(impl("foo"), (*iface)(nil)))
|
||||
require.NoError(t, err)
|
||||
err = callMethod("method", reflect.ValueOf(impl("??")), reflect.ValueOf(method), p.bindings)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "foo", saw)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user