cobra icon indicating copy to clipboard operation
cobra copied to clipboard

Passing in a common struct from rootCmd and its subcommands

Open esn89 opened this issue 1 year ago • 1 comments

I have a struct which will contain information about my cloud environments:

type foo struct {
	country     string
	region      string
	project     string
	environment string
}

I will init this root.go and have all the fields for this struct set.

My main issue now is that, I have code in the subcommands like:

rootcmd run --all or rootcmd destroy --all

that depend on the information provided by this foo struct. Such as which region I should be running, or which environment I should be destroying. How can I do something like this? Passing information and letting all sub/child commands know about it and use it.

esn89 avatar Jul 26 '23 17:07 esn89

I have a similar issue. Workarounds that I found are:

  • Declaring a global variable to hold the instance of that struct that will be passed to all commands. I don't like relying on global variables and even less mutating them, but it seems to be a philosophy that cobra has adopted nonetheless.
  • Populating the subcommand's Context with the populated instance of that struct, via the PersistentPreRun of the root command. Not ideal because Context brings 0 static typing or guarantees.

ErwanDL avatar Feb 29 '24 18:02 ErwanDL