Why doesn't Cobra see flags passed in CLI?

106 views Asked by At

For some reason flags stopped working in my cobra app. It worked before and now the same code doesn't read flags on 2 different machines for me. Defined flags get only default values for some reason.

I reproduced it with following steps:

mkdir foo
cd foo
go mod init "example.com/foo"
cobra-cli init

Then I added example run func to my root command:

Run: func(cmd *cobra.Command, args []string) {
    println("root command run")
},

and added init for flags in ./cmd/root.go:

var flag bool
var status string

func init() {
    log.SetFlags(0)

    rootCmd.Flags().BoolVarP(&flag, "flag", "f", false, "Some bool flag")
    rootCmd.Flags().StringVarP(&status, "status", "s", "status_default", "Sets a status")

    log.Printf("status is '%v'", status)
    log.Printf("flag is '%v'", flag)

    log.Printf("Received args: %v", os.Args[1:])
}

then I build and run the app

go build
./foo -f --status=baz

and get the following output:

status is 'status_default'
flag is 'false'
Received args: [-f --status=baz]
root command run

Expected that flag would be true and status would be baz. Can't understand why this happens. The same method for getting flags is shown in Cobra User Guide. Other sources that I found online also use this approach. What did I do wrong?

UPD Found the problem

Flags are not filled with values until command runs. So inside command run func I can read variables status and flag and they have values passed in CLI

0

There are 0 answers