Is there a way to add global options to a program that is applied to all commands? I'm trying to be able to define a single verbose and quiet flag that is applied not only to the program but to all commands added as well.
I can post sample code if necessary, but I think it's fairly self-explanatory.
It works as is:
Program
.version(Pkg.version)
.description(Pkg.description)
.options('-v, --verbose', 'be verbose')
.option('-q, --quiet', 'be quiet')
Program
.command('search <query>')
.description('do search')
.option('-r, --regex', 'use regex')
.action(function search (query, options) {
// Program.quite
// Program.verbose
// options.regex
});
Can I write a default action for an option? It is quite nice that I can create a "global option" which is passed to every command, but if I have many commands I don't want to call loggingFramework.setLogLevel(options.quite) everywhere.
I can't do commander.parse(process.argv); commander.opts();, because then the commands action is called _before_ I can do something with opts. But it looks I need to call parse before I can use options correctly.
And it looks like these global options aren't shown in the --help output of a command.
@donaldpipowitch Going through the source code and found this line. https://github.com/tj/commander.js/blob/master/index.js#L393
It seems to be possible as
Program.on('verbose', function () {
process.env.VERBOSE = this.verbose
})
Program.on('quiet', function () {
process.env.QUIET = this.quiet
})
Also for options that accept values, the value is passed to the callback function. For example
Program.on('env', function (env) {
process.env.NODE_ENV = env
})
some-command --env=production
Cool, thanks.
In addition to @donaldpipowitch's comment, in order to listen on the option event, we could use:
.option("--disable-tty", "disable tty")
.on("option:disable-tty", function() {
// do something here
})
The original question got answered, and I don't think there will be action due to the subsequent comments.
Feel free to open a new issue if it comes up again, with new information and renewed interest.
Thank you for your contributions.
Most helpful comment
@donaldpipowitch Going through the source code and found this line. https://github.com/tj/commander.js/blob/master/index.js#L393
It seems to be possible as
Also for options that accept values, the value is passed to the callback function. For example