diff --git a/index.js b/index.js index ca2c99d..9e3df12 100644 --- a/index.js +++ b/index.js @@ -3,7 +3,14 @@ var minimist = require('minimist'); module.exports = function parse (args, opts) { var level = 0, index; var args_ = []; - + var minopts = {}; + + for (var key in opts) { + if (opts.hasOwnProperty(key) && key !== 'forward') { + minopts[key] = opts[key]; + } + } + for (var i = 0; i < args.length; i++) { if (typeof args[i] === 'string' && /^\[/.test(args[i])) { if (level ++ === 0) { @@ -12,24 +19,24 @@ module.exports = function parse (args, opts) { } if (typeof args[i] === 'string' && /\]$/.test(args[i])) { if (-- level > 0) continue; - + var sub = args.slice(index, i + 1); if (typeof sub[0] === 'string') { sub[0] = sub[0].replace(/^\[/, ''); } if (sub[0] === '') sub.shift(); - + var n = sub.length - 1; if (typeof sub[n] === 'string') { sub[n] = sub[n].replace(/\]$/, ''); } if (sub[n] === '') sub.pop(); - - args_.push(parse(sub)); + + args_.push(parse(sub, opts && opts.forward && opts)); } else if (level === 0) args_.push(args[i]); } - - var argv = minimist(args_, opts); + + var argv = minimist(args_, minopts); return argv; }; diff --git a/readme.markdown b/readme.markdown index e77a4d9..cc3cb52 100644 --- a/readme.markdown +++ b/readme.markdown @@ -42,6 +42,12 @@ Parse the arguments array `args`, passing `opts` to An opening `[` in the `args` array creates a new context and a `]` closes a context. Contexts may be nested. +## options + +Specific to `subarg`, these options will not be forwarded to minimist. + +- `forward` recursively forward minimist options to nested contexts. + # install With [npm](https://npmjs.org) do: diff --git a/test/options.js b/test/options.js new file mode 100644 index 0000000..51ccfa6 --- /dev/null +++ b/test/options.js @@ -0,0 +1,50 @@ +var subarg = require('../'); +var test = require('tape'); + +test('forward options', function (t) { + var options = { + forward: true, + alias: { a: 'alpha', b: 'bravo', c: 'charlie' } + }; + + t.plan(1); + + t.deepEqual( + subarg('-a [ -b [ -c 1 ] --charlie 2 ] --bravo 3'.split(/\s+/), options), + { + _: [], + a: { + _: [], + b: { + _: [], + c: 1, + charlie: 1 + }, + bravo: { + _: [], + c: 1, + charlie: 1 + }, + c: 2, + charlie: 2 + }, + alpha: { + _: [], + b: { + _: [], + c: 1, + charlie: 1 + }, + bravo: { + _: [], + c: 1, + charlie: 1 + }, + c: 2, + charlie: 2 + }, + b: 3, + bravo: 3 + } + ); +});