Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Flag hook executed multiple times #377

Open
artemklevtsov opened this issue Sep 14, 2023 · 4 comments
Open

Flag hook executed multiple times #377

artemklevtsov opened this issue Sep 14, 2023 · 4 comments

Comments

@artemklevtsov
Copy link
Contributor

artemklevtsov commented Sep 14, 2023

Hi,

I tried to share flag across commands, but flag hook executed for the each defined command.

package main

import (
	"fmt"

	"github.com/alecthomas/kong"
)

var val string

type ValFlag string

func (f ValFlag) AfterApply() error {
	val = string(f)

	fmt.Printf("val=%s; flag=%s\n", val, f)

	return nil
}

type Cmd1 struct {
	Val ValFlag `default:"value1"`
}

func (cmd *Cmd1) Run() error {
	return nil
}

type Cmd2 struct {
	Val ValFlag `default:"value2"`
}

func (cmd *Cmd2) Run() error {
	return nil
}

type CLI struct {
	Cmd1 Cmd1 `cmd:""`
	Cmd2 Cmd2 `cmd:""`
}

func main() {
	var cli CLI

	parser, err := kong.New(
		&cli,
	)
	if err != nil {
		panic(err)
	}

	args := []string{"cmd-1", "--val=value3"}
	cliCtx, err := parser.Parse(args)
	if err != nil {
		panic(err)
	}

	if err := cliCtx.Run(); err != nil {
		cliCtx.FatalIfErrorf(err)
	}
}

Actual behavior:

val=value3; flag=value3
val=value2; flag=value2

Expected behavior:

val=value3; flag=value3
@alecthomas
Copy link
Owner

What's the issue you're seeing exactly?

@artemklevtsov
Copy link
Contributor Author

artemklevtsov commented Sep 14, 2023

val is overwritten with the cmd-2 val flag default value.

@artemklevtsov
Copy link
Contributor Author

artemklevtsov commented Sep 14, 2023

I use sync.Once as workaround:

var val string

type ValFlag string

var once sync.Once

func (f ValFlag) AfterApply() error {
	once.Do(func() { val = string(f) })

	fmt.Printf("val=%s; flag=%s\n", val, f)

	return nil
}

Output:

val=value3; flag=value3
val=value3; flag=value2

@artemklevtsov
Copy link
Contributor Author

My real use case is setup global logger options. I don't use global options because a several subcommands not support logging.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants