-
Notifications
You must be signed in to change notification settings - Fork 106
How to implement a negating flag
Lloyd Brookes edited this page Mar 27, 2020
·
2 revisions
You have a Boolean
flag defined, e.g. --dev
.
$ example --dev
You add dev: true
to your config file making it the default state. Now, you no longer need to set --dev
every time.
$ example
However, occasionally you might want to temporarity unset dev
mode at the command line. You need a negating flag.
$ example --no-dev
Command-line-args does not have a built-in opinion on how a negating flag should be defined (to enable users to name options in their own language). Here is an example implementation.
const commandLineArgs = require('command-line-args')
const optionDefinitions = [
{ name: 'dev', type: Boolean, defaultValue: true },
{ name: 'no-dev', type: Boolean }
]
const options = commandLineArgs(optionDefinitions)
const dev = options.dev && !options['no-dev']
console.log(`dev: ${dev}`)
$ node example.js
dev: true
$ node example.js --dev
dev: true
$ node example.js --dev --no-dev
dev: false
$ node example.js --no-dev
dev: false
You might not want to list --no-dev
as a separate option in the usage guide. If using command-line-usage, you can hide options in an optionList
section using options.hide
.
Here's a full example.
const commandLineArgs = require('command-line-args')
const optionDefinitions = [
{
name: 'dev',
type: Boolean,
defaultValue: true,
description: 'Set to enable dev mode. If already enabled, set --no-dev to disable.'
},
{ name: 'no-dev', type: Boolean },
{
name: 'help',
type: Boolean,
description: 'Display a usage guide.'
}
]
const options = commandLineArgs(optionDefinitions)
const dev = options.dev && !options['no-dev']
if (options.help) {
const commandLineUsage = require('command-line-usage')
const usage = commandLineUsage([
{
header: 'Options',
optionList: optionDefinitions,
hide: ['no-dev']
}
])
console.log(usage)
}
The --no-dev
option is defined but not displayed.
$ node example.js --help
Options
--dev Set to enable dev mode. If already enabled, set --no-dev to disable.
--help Display a usage guide.