cobra
cobra copied to clipboard
Add a Data map[string]any to store arbitrary command data
This PR aims to add an arbitrary map[string]any
field to the Command
type, so that consumer projects/plugins can store data pertaining to a given command, and for this data to share the same lifetime as the command itself.
An example related to #2019 and requested in #2083 is for completion plugins, which might need to store various completion data for commands, and in the case where the commands are being garbage-collected in a closed-loop console (such as this one, for this associated completion data to be correctly released along with the command itself.
The principle is the same as for command.Annotations
field, except that the values in the key/value pairs can be anything. Equally, initializing the map is left at the consumers' responsibility.
Shouldn't this be just a any
? Making this map[string]any
is already somewhat limiting depending on the use case. If this is just any
you can still put in a map[string]any
with that or if you do not need it you may directly store a value without having to go through the string map lookup.
Hello @Luap99, thanks for the input.
If several plugins/paths need different objects stored with the command, who decides who has precedence ?
If plugin A wants a struct on monday, and then on tuesday plugin B wants another, then it can only delete Plugin A struct to replace it.
Now plugin A can't work, because plugin B replaced the contents altogether, and it has no way of communicating it to plugin A.
So I think there is no way around a map here...
Yeah
Hello @Luap99, thanks for the input.
If several plugins/paths need different objects stored with the command, who decides who has precedence ?
If plugin A wants a struct on monday, and then on tuesday plugin B wants another, then it can only delete Plugin A struct to replace it.
Now plugin A can't work, because plugin B replaced the contents altogether, and it has no way of communicating it to plugin A.
So I think there is no way around a map here...
Ok yes that sounds like a valid reason for a map. I am not really sure how to common several plugins that need to store data attached to the command struct are but I guess it is better to be safe and use the map.
Maybe rethinking, is it really necessary to store the data inside the cobra command? Couldn't the "plugin" just define a wrapper type like
type PluginCommand struct {
*cobra.Command
data ...
}
and just accept this type in the plugin APIs?