I want to write a software which provides the contents of properties files (key=value), environment variables and command line flags as a unified map to the underlying template engine.
Is it possible in cobra to have flags which are "invented" by the user when invoking the command, e.g.
eb --myvar=myval
so that I will have a map { "myvar": "myval" } somewhere?
No, it's not possible.
Create flags by yourself for every config key as everyone does.
If you're able to read the properties file before executing Command you can create the Command hierarchy and add flags before calling Execute().
But if you want to receive a map, it might be easier to just have a single flag -o with a https://godoc.org/github.com/spf13/pflag#StringSlice and specify it multiple times.
-o myvar=myval -o other=myval2 ...
You can also create your own custom flag type that builds a map: http://godoc.org/github.com/docker/cli/opts#MapOpts
A third option is to use a -- before your custom flags, like: ./bin -- --myvar=myval. That way you receive the flags as args, and you can parse them yourself into a map.
Thanks for your help, @dnephin this looks like a feasible way. The point is, that I have no idea which flags the user will specify unless I would do a very costly analysis of the templates to render (which I don't know before I don't have the command line parsed), so using a -o flag multiple times for these user defined parameters is a brilliant idea.
@bogem: At coding toime I don't know what the user will feed to the application. If I would be able to read their minds in advance, I would not need to get command line flags, I would take the needed information from my crystal ball.
@joernott sorry for my dumb and angry answer.
@dnephin offered the best solution how cobra can solve your problem.
@bogem Sorry for snapping at you. I really like cobra and want to use it for my project and I couldn't see the simple solution right in front of my eyes.
@joernott You're always welcome in our community!
Most helpful comment
If you're able to read the properties file before executing
Commandyou can create theCommandhierarchy and add flags before callingExecute().But if you want to receive a map, it might be easier to just have a single flag
-owith a https://godoc.org/github.com/spf13/pflag#StringSlice and specify it multiple times.You can also create your own custom flag type that builds a map: http://godoc.org/github.com/docker/cli/opts#MapOpts
A third option is to use a
--before your custom flags, like:./bin -- --myvar=myval. That way you receive the flags as args, and you can parse them yourself into a map.