Skip to content

Document about parent command injection in subcommands #473

@Hritik14

Description

@Hritik14

I was looking for ways to access parent flags and got confused with the example on the README which uses a Context to achieve this.
Found an issue which states this more clearly: #121 (comment)

Currently: https://github.com/alecthomas/kong?tab=readme-ov-file#attach-a-run-error-method-to-each-command

type Context struct {
  Debug bool
}
// ...
var cli struct {
  Debug bool `help:"Enable debug mode."`

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

func main() {
  ctx := kong.Parse(&cli)
  err := ctx.Run(&Context{Debug: cli.Debug})

Wouldn't it make more sense to put it like mentioned in the linked issue

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

  Rm RmCmd `cmd:"" help:"Remove files."`
  Ls LsCmd `cmd:"" help:"List paths."`
}
// ...
func (l *LsCmd) Run(cli *CLI) error {
// use cli.Debug here !!
  fmt.Println("ls", l.Paths)
  return nil
}

func main() {
  var cli CLI
  ctx := kong.Parse(&cli)
  err := ctx.Run()

this highlights that calling ctx.Run() without arguments makes CLI available inside Run

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions