Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 14 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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;
};
6 changes: 6 additions & 0 deletions readme.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
50 changes: 50 additions & 0 deletions test/options.js
Original file line number Diff line number Diff line change
@@ -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
}
);
});