Allow binds to be provided by a function.

This is useful for situations where the initialisation of some object
should be deferred, eg. when there are distinct "setup" and "use" phases
to a tools lifecycle.
This commit is contained in:
Alec Thomas
2020-03-03 13:57:56 +11:00
parent c45ea59559
commit b8c82fea7c
6 changed files with 68 additions and 9 deletions
+26
View File
@@ -41,3 +41,29 @@ func TestBindTo(t *testing.T) {
require.NoError(t, err)
require.Equal(t, "foo", saw)
}
type bindToProviderCLI struct {
Called bool
Cmd bindToProviderCmd `cmd:""`
}
type boundThing struct {
}
type bindToProviderCmd struct{}
func (*bindToProviderCmd) Run(cli *bindToProviderCLI, b *boundThing) error {
cli.Called = true
return nil
}
func TestBindToProvider(t *testing.T) {
var cli bindToProviderCLI
app, err := New(&cli, BindToProvider(func() (*boundThing, error) { return &boundThing{}, nil }))
require.NoError(t, err)
ctx, err := app.Parse([]string{"cmd"})
require.NoError(t, err)
err = ctx.Run()
require.NoError(t, err)
require.True(t, cli.Called)
}