diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..91c336188 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,7 @@ +root = true + +[*.js] +end_of_line = lf +indent_style = space +indent_size = 2 +insert_final_newline = true diff --git a/lib/apply-extends.js b/lib/apply-extends.js new file mode 100644 index 000000000..d1014e5cf --- /dev/null +++ b/lib/apply-extends.js @@ -0,0 +1,19 @@ +var fs = require('fs') +var path = require('path') +var assign = require('./assign') + +function applyExtends (config, cwd) { + var defaultConfig = {} + + if (config.hasOwnProperty('extends')) { + var pathToDefault = path.join(cwd, config.extends) + delete config.extends + + defaultConfig = JSON.parse(fs.readFileSync(pathToDefault, 'utf8')) + defaultConfig = applyExtends(defaultConfig, path.dirname(pathToDefault)) + } + + return assign(defaultConfig, config) +} + +module.exports = applyExtends diff --git a/test/fixtures/extends/config_1.json b/test/fixtures/extends/config_1.json new file mode 100644 index 000000000..043fb87b0 --- /dev/null +++ b/test/fixtures/extends/config_1.json @@ -0,0 +1,5 @@ +{ + "a": 30, + "b": 22, + "extends": "./config_2.json" +} \ No newline at end of file diff --git a/test/fixtures/extends/config_2.json b/test/fixtures/extends/config_2.json new file mode 100644 index 000000000..886f419f4 --- /dev/null +++ b/test/fixtures/extends/config_2.json @@ -0,0 +1,3 @@ +{ + "z": 15 +} \ No newline at end of file diff --git a/test/yargs.js b/test/yargs.js index 5d5771df8..dd2430bd5 100644 --- a/test/yargs.js +++ b/test/yargs.js @@ -1155,6 +1155,21 @@ describe('yargs dsl tests', function () { argv.foo.should.equal(1) argv.bar.should.equal(2) }) + + describe('extends', function () { + it('applies default configurations when given config object', function () { + var argv = yargs + .config({ + extends: './test/fixtures/extends/config_1.json', + a: 1 + }) + .argv + + argv.a.should.equal(1) + argv.b.should.equal(22) + argv.z.should.equal(15) + }) + }) }) describe('normalize', function () { diff --git a/yargs.js b/yargs.js index b36812e5a..69b3c53b1 100644 --- a/yargs.js +++ b/yargs.js @@ -9,6 +9,7 @@ const Validation = require('./lib/validation') const Y18n = require('y18n') const objFilter = require('./lib/obj-filter') const setBlocking = require('set-blocking') +const applyExtends = require('./lib/apply-extends') const YError = require('./lib/yerror') var exports = module.exports = Yargs @@ -304,6 +305,7 @@ function Yargs (processArgs, cwd, parentRequire) { argsert('[object|string] [string|function] [function]', [key, msg, parseFn], arguments.length) // allow a config object to be provided directly. if (typeof key === 'object') { + key = applyExtends(key, cwd) options.configObjects = (options.configObjects || []).concat(key) return self } @@ -319,6 +321,7 @@ function Yargs (processArgs, cwd, parentRequire) { ;(Array.isArray(key) ? key : [key]).forEach(function (k) { options.config[k] = parseFn || true }) + return self }