How to merge flags, defined in other package, into cobra.flags?

780 views Asked by At

Some definition in sig.k8s.io/controller-runtime/pkg/client/config/config.go:

var (
    kubeconfig, apiServerURL string
)

func init() {
    flag.StringVar(&kubeconfig, "kubeconfig", "",
        "Paths to a kubeconfig. Only required if out-of-cluster.")
}

my project, mybinary, with cobra

var rootCmd = &cobra.Command{
    Use:   "mybinary",
    Run: func(cmd *cobra.Command, args []string) {
        somefunc()
    }
}
func init() {
    rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file")
    rootCmd.InitDefaultHelpFlag()
}

What do I need to do if I want to use mybinary --kubeconfig somevalue to set param kubeconfig defined upon config.go?

1

There are 1 answers

0
torek On

You have multiple options, but I think for now your best bet is probably to use cobra's PersistentPreRun function:

var rootCmd = &cobra.Command{
        // ...
        PersistentPreRun: func(cmd *cobra.Command, args []string) {
                flag.CommandLine.Parse([]string{"-kubeconfig", yourVariableHere})
        },
        // ...
}

That is, before your root command runs, or any of the commands that are derived from it (provided they don't override the PreRun), you'll call the equivalent of calling flag.Parse() as if someone had run:

your-program -kubeconfig <string>

where the value is from the argument provided to your own Cobra flag. You could use your cfgFile argument if that's the right thing, or add a --kubeconfig variable.

If you're using viper, it seems to have its own glue for mixing with the basic flag library, but I have not investigated this. I do see, in config.go, this comment:

// TODO: Fix this to allow double vendoring this library but still register flags on behalf of users

which, if fixed, would provide a way other than calling flag.CommandLine.Parse.