cobra
cobra copied to clipboard
Context only propagates to child commands the first time
I have an application that can be called in two ways:
- manually invoke from the CLI
- process directives in specially-formatted lines of a text file, which contain CLI arguments in the same format
For the second use case, I'm creating a Context
that I'm passing to ExecuteContext
for each of my directives. I noticed that the first time, sub-commands get my new context. However, for subsequent inputs the context is only updated on the root command.
Is this behaviour intentional? I can imagine this being overlooked as Cobra commands are typically executed only once for an instance of a program. I realize fixing this would cause a regression, so I'd like to propose something like this as an opt-in for the behaviour I was expecting:
func init() {
cobra.OverwriteChildContexts = true
}
Probably related to #908.
This issue is being marked as stale due to a long period of inactivity
Very similar to #1109
I've got the same trouble as well. I've bypassed it by traversing back to the root command and using its context instead of using the current cmd.Context()
Hacky, but it's working.
// ExtractContext traverse backwards to the root command and extracts the context
// of it.
// More info: https://github.com/spf13/cobra/issues/1469
func ExtractContext(cmd *cobra.Command) context.Context {
if cmd == nil {
return nil
}
var (
ctx = cmd.Context()
p = cmd.Parent()
)
if cmd.Parent() == nil {
return ctx
}
for {
ctx = p.Context()
p = p.Parent()
if p == nil {
break
}
}
return ctx
}