kong icon indicating copy to clipboard operation
kong copied to clipboard

envprefix not propagated to sub-commands

Open aderouineau opened this issue 6 months ago • 2 comments

Example program:

package main

import (
	"github.com/alecthomas/kong"
)

type CmdCLI struct {
	InnerFlag string `kong:"env=INNER_FLAG"`
}

type TestCLI struct {
	TopFlag string `kong:"env=TOP_FLAG"`

	Cmd CmdCLI `kong:"cmd,envprefix=CMD_"`
}

type WrapCLI struct {
	TestCLI `kong:"envprefix=APP_"`
}

func main() {
	kcli := WrapCLI{}

	kctx := kong.Parse(&kcli,
		kong.UsageOnError(),
	)
	err := kctx.Run()
	kctx.FatalIfErrorf(err)
}

Running it with cmd -h returns:

Usage: example cmd [flags]

Flags:
  -h, --help                 Show context-sensitive help.
      --top-flag=STRING      ($APP_TOP_FLAG)

      --inner-flag=STRING    ($INNER_FLAG)

I expected the environment variable for InnerFlag to be APP_CMD_INNER_FLAG.

aderouineau avatar Jun 24 '25 07:06 aderouineau

envprefix is not currently intended to work with sub-commands, only embedded flags, eg.

type EmbeddedFlags struct {
  Flag string `env:"BAR"`
}

type CLI struct {
  EmbeddedFlags `envprefix:"FOO_"`
}

It doesn't seem unreasonable to support this though.

alecthomas avatar Jun 24 '25 08:06 alecthomas

only embedded flags, eg.

Right, that's why I had included that in my example -- to show the contrast.

It doesn't seem unreasonable to support this though.

That would be great! I'm trying to read through build.go. It looks like envprefix gets propagated in flattenedFields(), but I don't yet understand how/why it's behaving differently between command and flag nodes.

aderouineau avatar Jun 24 '25 09:06 aderouineau