From 1c934d5a822d2e2bed237995256590e2ea31440f Mon Sep 17 00:00:00 2001 From: coderaiser Date: Thu, 11 May 2017 11:42:31 +0300 Subject: [PATCH] feature(config) add ability to override absent values in config --- server/config.js | 29 +++++++++++++---------------- test/server/config.js | 9 +++++---- 2 files changed, 18 insertions(+), 20 deletions(-) diff --git a/server/config.js b/server/config.js index 773f41cc..e085419f 100644 --- a/server/config.js +++ b/server/config.js @@ -24,28 +24,25 @@ const apiURL = CloudFunc.apiURL; const ConfigPath = path.join(DIR, 'json/config.json'); const ConfigHome = path.join(HOME, '.cloudcmd.json'); -const readjsonSync = (name) => jju.parse(fs.readFileSync(name, 'utf8'), { - mode: 'json' -}); +const readjsonSync = (name) => { + return jju.parse(fs.readFileSync(name, 'utf8'), { + mode: 'json' + }); +}; + +const rootConfig = readjsonSync(ConfigPath); const key = (a) => Object.keys(a).pop(); -let config; +let configHome; let error = tryCatch(() => { - config = readjsonSync(ConfigHome); + configHome = readjsonSync(ConfigHome); }); -if (error) { - if (error.code !== 'ENOENT') - console.error('cloudcmd --config ~/.cloudcmd.json:', error.message); - - error = tryCatch(() => { - config = readjsonSync(ConfigPath); - }); - - if (error) - exit('cloudcmd --config', ConfigPath + ':', error.message); -} +if (error && error.code !== 'ENOENT') + exit(`cloudcmd --config ${ConfigHome}: ${error.message}`); + +const config = Object.assign({}, rootConfig, configHome); module.exports = manage; module.exports.save = save; diff --git a/test/server/config.js b/test/server/config.js index be0b135d..da1d79ab 100644 --- a/test/server/config.js +++ b/test/server/config.js @@ -10,15 +10,15 @@ const root = '../../'; const dir = root + 'server/'; const config = require(dir + 'config'); -const pathConfig = path.join(os.homedir(), '.cloudcmd.json'); -const localConfig = path.join(__dirname, '..', '..', 'json', 'config.json'); +const pathHomeConfig = path.join(os.homedir(), '.cloudcmd.json'); +const pathConfig = path.join(__dirname, '..', '..', 'json', 'config.json'); const clean = (name) => { delete require.cache[require.resolve(name)]; }; function readConfig() { - return readjson.sync.try(pathConfig) || require(localConfig); + return readjson.sync.try(pathHomeConfig) || require(pathConfig); } const before = require('../before'); @@ -57,8 +57,9 @@ test('config: manage: get: *', (t) => { const config = require(dir + 'config'); const data = config('*'); + const expected = Object.assign({}, require(pathConfig), readConfig()); - t.deepEqual(data, readConfig(), 'should return config data'); + t.deepEqual(data, expected, 'should return config data'); t.end(); });