package/package.json000644 0000001267 13302370327011573 0ustar00000000 000000 { "name": "rc", "version": "1.2.8", "description": "hardwired configuration loader", "main": "index.js", "browser": "browser.js", "scripts": { "test": "set -e; node test/test.js; node test/ini.js; node test/nested-env-vars.js" }, "repository": { "type": "git", "url": "https://github.com/dominictarr/rc.git" }, "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", "keywords": [ "config", "rc", "unix", "defaults" ], "bin": "./cli.js", "author": "Dominic Tarr (dominictarr.com)", "dependencies": { "deep-extend": "^0.6.0", "ini": "~1.3.0", "minimist": "^1.2.0", "strip-json-comments": "~2.0.1" } } package/browser.js000644 0000000211 13271402304011306 0ustar00000000 000000 // when this is loaded into the browser, // just use the defaults... module.exports = function (name, defaults) { return defaults } package/cli.js000755 0000000155 13271402304010404 0ustar00000000 000000 #! /usr/bin/env node var rc = require('./index') console.log(JSON.stringify(rc(process.argv[2]), false, 2)) package/index.js000755 0000002737 13271402304010754 0ustar00000000 000000 var cc = require('./lib/utils') var join = require('path').join var deepExtend = require('deep-extend') var etc = '/etc' var win = process.platform === "win32" var home = win ? process.env.USERPROFILE : process.env.HOME module.exports = function (name, defaults, argv, parse) { if('string' !== typeof name) throw new Error('rc(name): name *must* be string') if(!argv) argv = require('minimist')(process.argv.slice(2)) defaults = ( 'string' === typeof defaults ? cc.json(defaults) : defaults ) || {} parse = parse || cc.parse var env = cc.env(name + '_') var configs = [defaults] var configFiles = [] function addConfigFile (file) { if (configFiles.indexOf(file) >= 0) return var fileConfig = cc.file(file) if (fileConfig) { configs.push(parse(fileConfig)) configFiles.push(file) } } // which files do we look at? if (!win) [join(etc, name, 'config'), join(etc, name + 'rc')].forEach(addConfigFile) if (home) [join(home, '.config', name, 'config'), join(home, '.config', name), join(home, '.' + name, 'config'), join(home, '.' + name + 'rc')].forEach(addConfigFile) addConfigFile(cc.find('.'+name+'rc')) if (env.config) addConfigFile(env.config) if (argv.config) addConfigFile(argv.config) return deepExtend.apply(null, configs.concat([ env, argv, configFiles.length ? {configs: configFiles, config: configFiles[configFiles.length - 1]} : undefined, ])) } package/LICENSE.APACHE2000644 0000001112 13271402304011275 0ustar00000000 000000 Apache License, Version 2.0 Copyright (c) 2011 Dominic Tarr Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. package/LICENSE.BSD000644 0000002754 13271402304010717 0ustar00000000 000000 Copyright (c) 2013, Dominic Tarr All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. package/LICENSE.MIT000644 0000002100 13271402304010721 0ustar00000000 000000 The MIT License Copyright (c) 2011 Dominic Tarr Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package/README.md000644 0000013536 13271402304010562 0ustar00000000 000000 # rc The non-configurable configuration loader for lazy people. ## Usage The only option is to pass rc the name of your app, and your default configuration. ```javascript var conf = require('rc')(appname, { //defaults go here. port: 2468, //defaults which are objects will be merged, not replaced views: { engine: 'jade' } }); ``` `rc` will return your configuration options merged with the defaults you specify. If you pass in a predefined defaults object, it will be mutated: ```javascript var conf = {}; require('rc')(appname, conf); ``` If `rc` finds any config files for your app, the returned config object will have a `configs` array containing their paths: ```javascript var appCfg = require('rc')(appname, conf); appCfg.configs[0] // /etc/appnamerc appCfg.configs[1] // /home/dominictarr/.config/appname appCfg.config // same as appCfg.configs[appCfg.configs.length - 1] ``` ## Standards Given your application name (`appname`), rc will look in all the obvious places for configuration. * command line arguments, parsed by minimist _(e.g. `--foo baz`, also nested: `--foo.bar=baz`)_ * environment variables prefixed with `${appname}_` * or use "\_\_" to indicate nested properties
_(e.g. `appname_foo__bar__baz` => `foo.bar.baz`)_ * if you passed an option `--config file` then from that file * a local `.${appname}rc` or the first found looking in `./ ../ ../../ ../../../` etc. * `$HOME/.${appname}rc` * `$HOME/.${appname}/config` * `$HOME/.config/${appname}` * `$HOME/.config/${appname}/config` * `/etc/${appname}rc` * `/etc/${appname}/config` * the defaults object you passed in. All configuration sources that were found will be flattened into one object, so that sources **earlier** in this list override later ones. ## Configuration File Formats Configuration files (e.g. `.appnamerc`) may be in either [json](http://json.org/example) or [ini](http://en.wikipedia.org/wiki/INI_file) format. **No** file extension (`.json` or `.ini`) should be used. The example configurations below are equivalent: #### Formatted as `ini` ``` ; You can include comments in `ini` format if you want. dependsOn=0.10.0 ; `rc` has built-in support for ini sections, see? [commands] www = ./commands/www console = ./commands/repl ; You can even do nested sections [generators.options] engine = ejs [generators.modules] new = generate-new engine = generate-backend ``` #### Formatted as `json` ```javascript { // You can even comment your JSON, if you want "dependsOn": "0.10.0", "commands": { "www": "./commands/www", "console": "./commands/repl" }, "generators": { "options": { "engine": "ejs" }, "modules": { "new": "generate-new", "backend": "generate-backend" } } } ``` Comments are stripped from JSON config via [strip-json-comments](https://github.com/sindresorhus/strip-json-comments). > Since ini, and env variables do not have a standard for types, your application needs be prepared for strings. To ensure that string representations of booleans and numbers are always converted into their proper types (especially useful if you intend to do strict `===` comparisons), consider using a module such as [parse-strings-in-object](https://github.com/anselanza/parse-strings-in-object) to wrap the config object returned from rc. ## Simple example demonstrating precedence Assume you have an application like this (notice the hard-coded defaults passed to rc): ``` const conf = require('rc')('myapp', { port: 12345, mode: 'test' }); console.log(JSON.stringify(conf, null, 2)); ``` You also have a file `config.json`, with these contents: ``` { "port": 9000, "foo": "from config json", "something": "else" } ``` And a file `.myapprc` in the same folder, with these contents: ``` { "port": "3001", "foo": "bar" } ``` Here is the expected output from various commands: `node .` ``` { "port": "3001", "mode": "test", "foo": "bar", "_": [], "configs": [ "/Users/stephen/repos/conftest/.myapprc" ], "config": "/Users/stephen/repos/conftest/.myapprc" } ``` *Default `mode` from hard-coded object is retained, but port is overridden by `.myapprc` file (automatically found based on appname match), and `foo` is added.* `node . --foo baz` ``` { "port": "3001", "mode": "test", "foo": "baz", "_": [], "configs": [ "/Users/stephen/repos/conftest/.myapprc" ], "config": "/Users/stephen/repos/conftest/.myapprc" } ``` *Same result as above but `foo` is overridden because command-line arguments take precedence over `.myapprc` file.* `node . --foo barbar --config config.json` ``` { "port": 9000, "mode": "test", "foo": "barbar", "something": "else", "_": [], "config": "config.json", "configs": [ "/Users/stephen/repos/conftest/.myapprc", "config.json" ] } ``` *Now the `port` comes from the `config.json` file specified (overriding the value from `.myapprc`), and `foo` value is overriden by command-line despite also being specified in the `config.json` file.* ## Advanced Usage #### Pass in your own `argv` You may pass in your own `argv` as the third argument to `rc`. This is in case you want to [use your own command-line opts parser](https://github.com/dominictarr/rc/pull/12). ```javascript require('rc')(appname, defaults, customArgvParser); ``` ## Pass in your own parser If you have a special need to use a non-standard parser, you can do so by passing in the parser as the 4th argument. (leave the 3rd as null to get the default args parser) ```javascript require('rc')(appname, defaults, null, parser); ``` This may also be used to force a more strict format, such as strict, valid JSON only. ## Note on Performance `rc` is running `fs.statSync`-- so make sure you don't use it in a hot code path (e.g. a request handler) ## License Multi-licensed under the two-clause BSD License, MIT License, or Apache License, version 2.0 package/lib/utils.js000644 0000005307 13271402304011544 0ustar00000000 000000 'use strict'; var fs = require('fs') var ini = require('ini') var path = require('path') var stripJsonComments = require('strip-json-comments') var parse = exports.parse = function (content) { //if it ends in .json or starts with { then it must be json. //must be done this way, because ini accepts everything. //can't just try and parse it and let it throw if it's not ini. //everything is ini. even json with a syntax error. if(/^\s*{/.test(content)) return JSON.parse(stripJsonComments(content)) return ini.parse(content) } var file = exports.file = function () { var args = [].slice.call(arguments).filter(function (arg) { return arg != null }) //path.join breaks if it's a not a string, so just skip this. for(var i in args) if('string' !== typeof args[i]) return var file = path.join.apply(null, args) var content try { return fs.readFileSync(file,'utf-8') } catch (err) { return } } var json = exports.json = function () { var content = file.apply(null, arguments) return content ? parse(content) : null } var env = exports.env = function (prefix, env) { env = env || process.env var obj = {} var l = prefix.length for(var k in env) { if(k.toLowerCase().indexOf(prefix.toLowerCase()) === 0) { var keypath = k.substring(l).split('__') // Trim empty strings from keypath array var _emptyStringIndex while ((_emptyStringIndex=keypath.indexOf('')) > -1) { keypath.splice(_emptyStringIndex, 1) } var cursor = obj keypath.forEach(function _buildSubObj(_subkey,i){ // (check for _subkey first so we ignore empty strings) // (check for cursor to avoid assignment to primitive objects) if (!_subkey || typeof cursor !== 'object') return // If this is the last key, just stuff the value in there // Assigns actual value from env variable to final key // (unless it's just an empty string- in that case use the last valid key) if (i === keypath.length-1) cursor[_subkey] = env[k] // Build sub-object if nothing already exists at the keypath if (cursor[_subkey] === undefined) cursor[_subkey] = {} // Increment cursor used to track the object at the current depth cursor = cursor[_subkey] }) } } return obj } var find = exports.find = function () { var rel = path.join.apply(null, [].slice.call(arguments)) function find(start, rel) { var file = path.join(start, rel) try { fs.statSync(file) return file } catch (err) { if(path.dirname(start) !== start) // root return find(path.dirname(start), rel) } } return find(process.cwd(), rel) } package/test/ini.js000644 0000000470 13271402304011370 0ustar00000000 000000 var cc =require('../lib/utils') var INI = require('ini') var assert = require('assert') function test(obj) { var _json, _ini var json = cc.parse (_json = JSON.stringify(obj)) var ini = cc.parse (_ini = INI.stringify(obj)) console.log(_ini, _json) assert.deepEqual(json, ini) } test({hello: true}) package/test/nested-env-vars.js000644 0000002560 13271402304013634 0ustar00000000 000000 var seed = Math.random(); var n = 'rc'+ seed; var N = 'RC'+ seed; var assert = require('assert') // Basic usage process.env[n+'_someOpt__a'] = 42 process.env[n+'_someOpt__x__'] = 99 process.env[n+'_someOpt__a__b'] = 186 process.env[n+'_someOpt__a__b__c'] = 243 process.env[n+'_someOpt__x__y'] = 1862 process.env[n+'_someOpt__z'] = 186577 // Should ignore empty strings from orphaned '__' process.env[n+'_someOpt__z__x__'] = 18629 process.env[n+'_someOpt__w__w__'] = 18629 // Leading '__' should ignore everything up to 'z' process.env[n+'___z__i__'] = 9999 // should ignore case for config name section. process.env[N+'_test_upperCase'] = 187 function testPrefix(prefix) { var config = require('../')(prefix, { option: true }) console.log('\n\n------ nested-env-vars ------\n',{prefix: prefix}, '\n', config); assert.equal(config.option, true) assert.equal(config.someOpt.a, 42) assert.equal(config.someOpt.x, 99) // Should not override `a` once it's been set assert.equal(config.someOpt.a/*.b*/, 42) // Should not override `x` once it's been set assert.equal(config.someOpt.x/*.y*/, 99) assert.equal(config.someOpt.z, 186577) // Should not override `z` once it's been set assert.equal(config.someOpt.z/*.x*/, 186577) assert.equal(config.someOpt.w.w, 18629) assert.equal(config.z.i, 9999) assert.equal(config.test_upperCase, 187) } testPrefix(n); testPrefix(N); package/test/test.js000644 0000002230 13271402304011564 0ustar00000000 000000 var n = 'rc'+Math.random() var assert = require('assert') process.env[n+'_envOption'] = 42 var config = require('../')(n, { option: true }) console.log(config) assert.equal(config.option, true) assert.equal(config.envOption, 42) var customArgv = require('../')(n, { option: true }, { // nopt-like argv option: false, envOption: 24, argv: { remain: [], cooked: ['--no-option', '--envOption', '24'], original: ['--no-option', '--envOption=24'] } }) console.log(customArgv) assert.equal(customArgv.option, false) assert.equal(customArgv.envOption, 24) var fs = require('fs') var path = require('path') var jsonrc = path.resolve('.' + n + 'rc'); fs.writeFileSync(jsonrc, [ '{', '// json overrides default', '"option": false,', '/* env overrides json */', '"envOption": 24', '}' ].join('\n')); var commentedJSON = require('../')(n, { option: true }) fs.unlinkSync(jsonrc); console.log(commentedJSON) assert.equal(commentedJSON.option, false) assert.equal(commentedJSON.envOption, 42) assert.equal(commentedJSON.config, jsonrc) assert.equal(commentedJSON.configs.length, 1) assert.equal(commentedJSON.configs[0], jsonrc)