From 321c33e755485faaeb44eeb1c05d33b2e0a5a7c4 Mon Sep 17 00:00:00 2001 From: Stephane Le Cornec Date: Wed, 28 Aug 2013 15:44:54 -0400 Subject: [PATCH] allow dotted aliases & defaults --- index.js | 23 +++++++++++++++++------ test/dotted.js | 16 ++++++++++++++++ 2 files changed, 33 insertions(+), 6 deletions(-) create mode 100644 test/dotted.js diff --git a/index.js b/index.js index 5628b80..4319911 100644 --- a/index.js +++ b/index.js @@ -35,7 +35,7 @@ module.exports = function (args, opts) { setKey(argv, key.split('.'), value); (aliases[key] || []).forEach(function (x) { - argv[x] = argv[key]; + setKey(argv, x.split('.'), value); }); } @@ -129,17 +129,28 @@ module.exports = function (args, opts) { } Object.keys(defaults).forEach(function (key) { - if (!(key in argv)) { - argv[key] = defaults[key]; - if (key in aliases) { - argv[aliases[key]] = defaults[key]; - } + if (!hasKey(argv, key.split('.'))) { + setKey(argv, key.split('.'), defaults[key]); + + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), defaults[key]); + }); } }); return argv; }; +function hasKey (obj, keys) { + var o = obj; + keys.slice(0,-1).forEach(function (key) { + o = (o[key] || {}); + }); + + var key = keys[keys.length - 1]; + return key in o; +} + function setKey (obj, keys, value) { var o = obj; keys.slice(0,-1).forEach(function (key) { diff --git a/test/dotted.js b/test/dotted.js new file mode 100644 index 0000000..ef0ae34 --- /dev/null +++ b/test/dotted.js @@ -0,0 +1,16 @@ +var parse = require('../'); +var test = require('tape'); + +test('dotted alias', function (t) { + var argv = parse(['--a.b', '22'], {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}}); + t.equal(argv.a.b, 22); + t.equal(argv.aa.bb, 22); + t.end(); +}); + +test('dotted default', function (t) { + var argv = parse('', {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}}); + t.equal(argv.a.b, 11); + t.equal(argv.aa.bb, 11); + t.end(); +});