From 1e6f15faac463b6a5e2f1ff63aaab9677b92cdfc Mon Sep 17 00:00:00 2001 From: Artem Klevtsov Date: Sun, 17 Sep 2023 06:39:43 +0700 Subject: [PATCH] Add EnvFlag util (#378) --- README.md | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 35b07c6..d465dba 100644 --- a/README.md +++ b/README.md @@ -337,6 +337,40 @@ 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. @@ -704,4 +738,4 @@ See the [section on hooks](#hooks-beforeresolve-beforeapply-afterapply-and-the-b ### Other options -The full set of options can be found [here](https://godoc.org/github.com/alecthomas/kong#Option). \ No newline at end of file +The full set of options can be found [here](https://godoc.org/github.com/alecthomas/kong#Option).