From 00bde7d60c433c188f2529a33bab187d40645f7d Mon Sep 17 00:00:00 2001 From: Tarn Burton Date: Thu, 10 Aug 2017 01:26:52 -0400 Subject: [PATCH] feat: allow configuration of prefix for boolean negation (#94) --- README.md | 19 +++++++++++++++++++ index.js | 6 ++++-- test/yargs-parser.js | 10 ++++++++++ 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d1817fcc..a368e632 100644 --- a/README.md +++ b/README.md @@ -250,6 +250,25 @@ node example.js -x 1 2 -x 3 4 { _: [], x: [[1, 2], [3, 4]] } ``` +### negation prefix + +* default: `no-` +* key: `negation-prefix` + +The prefix to use for negated boolean variables. + +```sh +node example.js --no-foo +{ _: [], foo: false } +``` + +_if set to `quux`:_ + +```sh +node example.js --quuxfoo +{ _: [], foo: false } +``` + ### populate -- * default: `false`. diff --git a/index.js b/index.js index 73154066..2ab9c2cc 100644 --- a/index.js +++ b/index.js @@ -16,6 +16,7 @@ function parse (args, opts) { 'dot-notation': true, 'parse-numbers': true, 'boolean-negation': true, + 'negation-prefix': 'no-', 'duplicate-arguments-array': true, 'flatten-duplicate-arrays': true, 'populate--': false @@ -45,6 +46,7 @@ function parse (args, opts) { coercions: {} } var negative = /^-[0-9]+(\.[0-9]+)?/ + var negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)') ;[].concat(opts.array).filter(Boolean).forEach(function (key) { flags.arrays[key] = true @@ -141,8 +143,8 @@ function parse (args, opts) { } else { setArg(m[1], m[2]) } - } else if (arg.match(/^--no-.+/) && configuration['boolean-negation']) { - key = arg.match(/^--no-(.+)/)[1] + } else if (arg.match(negatedBoolean) && configuration['boolean-negation']) { + key = arg.match(negatedBoolean)[1] setArg(key, false) // -- seperated by space. diff --git a/test/yargs-parser.js b/test/yargs-parser.js index 373f8d3c..fa296b6c 100644 --- a/test/yargs-parser.js +++ b/test/yargs-parser.js @@ -1968,6 +1968,16 @@ describe('yargs-parser', function () { parsed['no-dice'].should.equal(true) expect(parsed.dice).to.equal(undefined) }) + + it('negates boolean arguments with correct prefix', function () { + var parsed = parser(['--foodice'], { + configuration: { + 'negation-prefix': 'foo' + } + }) + + expect(parsed['dice']).to.equal(false) + }) }) describe('duplicate arguments array', function () {