cobra
cobra copied to clipboard
[Feature Request] Command-Specific Initializers
It would be nice to have command-specific initializers in addition to the global ones:
Changes in command.go
func (c *Command) OnInitialize(y ...func()) {
c.initializers = append(c.initializers, y...)
}
func (c *Command) preRun() {
for _, x := range initializers {
x()
}
for _, x := range c.initializers {
x()
}
}
Usage
func init() {
cmd := &cobra.Command{...}
cmd.OnInitialize(func() {
// do sth
})
}
Since preRun
is already a method of Command
and not a global func, having-command specific initializers only seems logical to me.
Additional context
I have a use case where I'd like to hook into the command execution and manipulate the args before they're passed to the command's *Run
/*RunE
funcs. I could use the global initializers but it doesn't feel right to use them for command specific logic, and in addition I have to verify that the command is actually the one being executed, to avoid execution of the initializer for other commands, which feels like a hack.
The Cobra project currently lacks enough contributors to adequately respond to all issues. This bot triages issues and PRs according to the following rules:
- After 60d of inactivity, lifecycle/stale is applied. - After 30d of inactivity since lifecycle/stale was applied, lifecycle/rotten is applied and the issue is closed. You can:
- Make a comment to remove the stale label and show your support. The 60 days reset. - If an issue has lifecycle/rotten and is closed, comment and ask maintainers if they'd be interseted in reopening
I'm also keen on this capability :)
@mbalsam82 I know it's not a perfect solution at all, but I checked for c.CalledAs()
in my OnInitialize
callback to see if the command I bound the callback in is the one being called or not.
// If the local 'c' command doesn't have a value for CalledAs() then we can skip this step
// since the local 'c' is not the one being executed anyway.
//
// Cobra only sets this property on the command being executed.
func (c *Command[ConfigModel, DataModel]) IsThisCommandBeingCalled() bool {
return c.CalledAs() != ""
}
The Cobra project currently lacks enough contributors to adequately respond to all issues. This bot triages issues and PRs according to the following rules:
- After 60d of inactivity, lifecycle/stale is applied. - After 30d of inactivity since lifecycle/stale was applied, lifecycle/rotten is applied and the issue is closed. You can:
- Make a comment to remove the stale label and show your support. The 60 days reset. - If an issue has lifecycle/rotten and is closed, comment and ask maintainers if they'd be interested in reopening