Skip to content
Merged
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
7 changes: 7 additions & 0 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,13 @@ func BindTo(impl, iface any) Option {
})
}

// BindFor allows binding of implementations to the compile-time type. It
// is equivalent to BindTo(v, (*T)(nil)), but can usually infer the
// correct type T.
func BindFor[T any](v T) Option {
return BindTo(v, (*T)(nil))
}

// BindToProvider binds an injected value to a provider function.
//
// The provider function must have one of the following signatures:
Expand Down
18 changes: 18 additions & 0 deletions options_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package kong

import (
"context"
"reflect"
"strings"
"testing"
Expand Down Expand Up @@ -43,6 +44,23 @@ func TestBindTo(t *testing.T) {
assert.Equal(t, "foo", saw)
}

func TestBindFor(t *testing.T) {
type key struct{}
var saw any
method := func(ctx context.Context) error {
saw = ctx.Value(key{})
return nil
}

var cli struct{}

p, err := New(&cli, BindFor(context.WithValue(context.Background(), key{}, "foo")))
assert.NoError(t, err)
err = callFunction(reflect.ValueOf(method), p.bindings)
assert.NoError(t, err)
assert.Equal(t, "foo", saw)
}

func TestInvalidCallback(t *testing.T) {
type iface interface {
Method()
Expand Down