From f84f9a910ecbb05f10a2254a7dc9d1b9eac5e64e Mon Sep 17 00:00:00 2001 From: Erwan Ameil Date: Wed, 30 Nov 2016 13:36:41 +0000 Subject: [PATCH] Allow several options objects or files on the command line --- index.js | 29 +++++++++++++++++++++++++---- test/index.js | 13 +++++++++++++ 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/index.js b/index.js index 84cbe42..7e5a7cd 100644 --- a/index.js +++ b/index.js @@ -28,7 +28,7 @@ program 'pug-cli version: ' + require( './package.json').version ) .usage('[options] [dir|file ...]') - .option('-O, --obj ', 'JSON/JavaScript options object or file') + .option('-O, --obj ', 'JSON/JavaScript options object or file', collectObj, []) .option('-o, --out ', 'output the rendered HTML or compiled JavaScript to ') .option('-p, --path ', 'filename used to resolve includes') .option('-b, --basedir ', 'path used as root directory to resolve absolute includes') @@ -78,7 +78,28 @@ program.parse(process.argv); // options given, parse them if (program.obj) { - options = parseObj(program.obj); + options = mergeObjs(program.obj); +} + +function collectObj (obj, obj_list) { + obj_list.push(obj); + return obj_list; +} + +/** + * Merge all options objects or files passed with the --obj/-O switch. + */ +function mergeObjs(objs) { + var options = {}; + for (var i = 0; i < objs.length; i++) { + var obj = parseObj(objs[i]); + for (var key in obj) { + if (obj.hasOwnProperty(key)) { + options[key] = obj[key]; + } + } + } + return options; } /** @@ -91,9 +112,9 @@ function parseObj (input) { } catch (e) { var str; try { - str = fs.readFileSync(program.obj, 'utf8'); + str = fs.readFileSync(input, 'utf8'); } catch (e) { - str = program.obj; + str = input; } try { return JSON.parse(str); diff --git a/test/index.js b/test/index.js index 5091a7f..63fb3cf 100644 --- a/test/index.js +++ b/test/index.js @@ -245,6 +245,19 @@ describe('HTML output', function () { done(); }); }); + it('Multiple options objects', function (done) { + w('obj1.json', '{"loc":"str1", onlyinobj1:"str1"}'); + w('obj2.json', '{"loc":"str2", onlyinobj2:"str2"}'); + w('input.pug', '.foo(from1=onlyinobj1 from2=onlyinobj2)= loc'); + w('input.html', '

output not written

'); + run(['--no-debug', '--obj', 'obj1.json', '--obj', 'obj2.json', 'input.pug'], + function (err) { + if (err) return done(err); + var html = r('input.html'); + assert(html === '
str2
'); + done(); + }); + }); }); it('stdio', function (done) { w('input.pug', '.foo bar');