Skip to content

Commit

Permalink
Document about binds with example (#491)
Browse files Browse the repository at this point in the history
  • Loading branch information
Hritik14 authored Jan 24, 2025
1 parent 8d238c8 commit 042a325
Showing 1 changed file with 37 additions and 4 deletions.
41 changes: 37 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
- [Command handling](#command-handling)
- [Switch on the command string](#switch-on-the-command-string)
- [Attach a `Run(...) error` method to each command](#attach-a-run-error-method-to-each-command)
- [Hooks: BeforeReset(), BeforeResolve(), BeforeApply(), AfterApply() and the Bind() option](#hooks-beforereset-beforeresolve-beforeapply-afterapply-and-the-bind-option)
- [Hooks: BeforeReset(), BeforeResolve(), BeforeApply(), AfterApply()](#hooks-beforereset-beforeresolve-beforeapply-afterapply)
- [The Bind() option](#the-bind-option)
- [Flags](#flags)
- [Commands and sub-commands](#commands-and-sub-commands)
- [Branching positional arguments](#branching-positional-arguments)
Expand Down Expand Up @@ -305,7 +306,7 @@ func main() {

```

## Hooks: BeforeReset(), BeforeResolve(), BeforeApply(), AfterApply() and the Bind() option
## Hooks: BeforeReset(), BeforeResolve(), BeforeApply(), AfterApply()

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
Expand All @@ -314,8 +315,6 @@ and after validation/assignment, respectively.

The `--help` flag is implemented with a `BeforeReset` hook.

Arguments to hooks are provided via the `Run(...)` method or `Bind(...)` option. `*Kong`, `*Context` and `*Path` are also bound and finally, hooks can also contribute bindings via `kong.Context.Bind()` and `kong.Context.BindTo()`.

eg.

```go
Expand All @@ -341,6 +340,40 @@ func main() {
}
```

## The Bind() option

Arguments to hooks are provided via the `Run(...)` method or `Bind(...)` option. `*Kong`, `*Context`, `*Path` and parent commands are also bound and finally, hooks can also contribute bindings via `kong.Context.Bind()` and `kong.Context.BindTo()`.

eg:

```go
type CLI struct {
Debug bool `help:"Enable debug mode."`

Rm RmCmd `cmd:"" help:"Remove files."`
Ls LsCmd `cmd:"" help:"List paths."`
}

type AuthorName string

// ...
func (l *LsCmd) Run(cli *CLI) error {
// use cli.Debug here !!
return nil
}

func (r *RmCmD) Run(author AuthorName) error{
// use binded author here
return nil
}

func main() {
var cli CLI

ctx := kong.Parse(&cli, Bind(AuthorName("penguin")))
err := ctx.Run()
```
## 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.
Expand Down

0 comments on commit 042a325

Please sign in to comment.