cobra
cobra copied to clipboard
Passing in a common struct from rootCmd and its subcommands
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.
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 thePersistentPreRun
of the root command. Not ideal becauseContext
brings 0 static typing or guarantees.