feat: allow hooks to be declared on embedded fields

Specifically, on Go embedded fields, not on fields tagged with `embed`.

Fixes #90.
This commit is contained in:
Alec Thomas
2024-12-27 13:41:00 +11:00
parent 565ae9b740
commit 840220c2ed
4 changed files with 75 additions and 53 deletions
+2 -36
View File
@@ -307,8 +307,8 @@ func main() {
## Hooks: BeforeReset(), BeforeResolve(), BeforeApply(), AfterApply() and the Bind() option
If a node in the grammar has a `BeforeReset(...)`, `BeforeResolve
(...)`, `BeforeApply(...) error` and/or `AfterApply(...) error` method, those
If a node in the CLI, or any of its embedded fields, has a `BeforeReset(...) error`, `BeforeResolve
(...) error`, `BeforeApply(...) error` and/or `AfterApply(...) error` method, those
methods will be called before values are reset, before validation/assignment,
and after validation/assignment, respectively.
@@ -341,40 +341,6 @@ func main() {
}
```
Another example of using hooks is load the env-file:
```go
package main
import (
"fmt"
"github.com/alecthomas/kong"
"github.com/joho/godotenv"
)
type EnvFlag string
// BeforeResolve loads env file.
func (c EnvFlag) BeforeReset(ctx *kong.Context, trace *kong.Path) error {
path := string(ctx.FlagValue(trace.Flag).(EnvFlag)) // nolint
path = kong.ExpandPath(path)
if err := godotenv.Load(path); err != nil {
return err
}
return nil
}
var CLI struct {
EnvFile EnvFlag
Flag `env:"FLAG"`
}
func main() {
_ = kong.Parse(&CLI)
fmt.Println(CLI.Flag)
}
```
## Flags
Any [mapped](#mapper---customising-how-the-command-line-is-mapped-to-go-values) field in the command structure _not_ tagged with `cmd` or `arg` will be a flag. Flags are optional by default.