cobra icon indicating copy to clipboard operation
cobra copied to clipboard

Add a Data map[string]any to store arbitrary command data

Open maxlandon opened this issue 1 year ago • 4 comments

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.

maxlandon avatar Dec 04 '23 07:12 maxlandon

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.

Luap99 avatar Dec 05 '23 10:12 Luap99

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...

maxlandon avatar Dec 05 '23 10:12 maxlandon

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?

Luap99 avatar Dec 28 '23 14:12 Luap99