Support for adding bindings to the Context.

This is very useful for hooks to pre-construct objects that can be used
by all subsequent downstream commands, for example.
This commit is contained in:
Alec Thomas
2018-09-27 14:20:16 +10:00
parent 5d7703774f
commit f72f53d947
5 changed files with 54 additions and 29 deletions
+26
View File
@@ -662,3 +662,29 @@ func TestEnum(t *testing.T) {
_, err := mustNew(t, &cli).Parse([]string{"--flag", "d"})
require.EqualError(t, err, "--flag=STRING must be one of a,b,c but got \"\"")
}
type commandWithHook struct {
value string
}
func (c *commandWithHook) AfterApply(cli *cliWithHook) error {
c.value = cli.Flag
return nil
}
type cliWithHook struct {
Flag string
Command commandWithHook `cmd:""`
}
func (c *cliWithHook) AfterApply(ctx *kong.Context) error {
ctx.Bind(c)
return nil
}
func TestParentBindings(t *testing.T) {
cli := &cliWithHook{}
_, err := mustNew(t, cli).Parse([]string{"command", "--flag=foo"})
require.NoError(t, err)
require.Equal(t, "foo", cli.Command.value)
}