diff --git a/Makefile b/Makefile index 6841acb..ce68c79 100644 --- a/Makefile +++ b/Makefile @@ -1,12 +1,9 @@ clean: - npm cache clean && rm -rf node_modules/* + rm -rf node_modules/* install: npm install -update: - make clean && rm -rf npm-shrinkwrap.json && npm install && npm shrinkwrap - test: ./node_modules/.bin/jshint lib/* --config test/jshint/config.json @NODE_ENV=test ./node_modules/.bin/mocha --recursive --reporter spec --timeout 3000 test diff --git a/README.md b/README.md index 0825b97..8b9b5eb 100644 --- a/README.md +++ b/README.md @@ -9,11 +9,30 @@ Opter provides an easy way to specify options for your application. It uses [com [![Build Status](https://secure.travis-ci.org/mac-/opter.png)](http://travis-ci.org/mac-/opter) [![Coverage Status](https://coveralls.io/repos/mac-/opter/badge.png)](https://coveralls.io/r/mac-/opter) +[![Code Climate](https://codeclimate.com/github/mac-/opter.png)](https://codeclimate.com/github/mac-/opter) [![NPM version](https://badge.fury.io/js/opter.png)](http://badge.fury.io/js/opter) [![Dependency Status](https://david-dm.org/mac-/opter.png)](https://david-dm.org/mac-/opter) [![NPM](https://nodei.co/npm/opter.png?downloads=true&stars=true)](https://nodei.co/npm/opter/) +## Contributing + +This module makes use of a `Makefile` for building/testing purposes. After obtaining a copy of the repo, run the following commands to make sure everything is in working condition before you start your work: + + make install + make test + +Before committing a change to your fork/branch, run the following commands to make sure nothing is broken: + + make test + make test-cov + +Don't forget to bump the version in the `package.json` using the [semver](http://semver.org/spec/v2.0.0.html) spec as a guide for which part to bump. Submit a pull request when your work is complete. + +***Notes:*** +* Please do your best to ensure the code coverage does not drop. If new unit tests are required to maintain the same level of coverage, please include those in your pull request. +* Please follow the same coding/formatting practices that have been established in the module. + ## Installation npm install opter @@ -28,13 +47,15 @@ The opter function takes two parameters: The object containing the options should be formatted like so: { - myOption: { // correlates to command line option "--my-option" or environment variable "myOption" or opter.json property "myOption" - character: 'm', // optional, used as the short option for the command line. If not provided opter will try to pick one for you based on your option name. - argument: 'string', // optional, describes what the value should be. If not provided, the type is expected to be a boolean, and does not require value when the option is specified on the command line (the presence of the option on the command line implies true) + myOption: { // correlates to command line option "--my-option" and environment variable "myOption" and environment variable "MYOPTION" and opter.json property "myOption" + character: 'm', // optional, used as the short option for the command line. If not provided opter will try to pick one for you based on your option name. + argument: 'string', // optional, describes what the value should be. If not provided, it defaults to the "type" within the schema if set, otherwise to "string". If the schema type is "boolean", no argument is required. defaultValue: 'fnord', // optional, the value to set the option to if it wasn't specified in the args or env vars - description: 'Some description', // optional, describes the option, - required: true, // optional, if set to true and no value is found, opter will throw an error. defaults to false. - type: Number // optional, the type to convert the data to. valid values are Boolean, Number, Date, Object and String. defaults to String. + required: true, // optional, if set to true and no value is found, opter will throw an error. defaults to false. + schema: { // optional, a JSONSchema definition to validate the value against. If the "type" property is used, opter will also try to convert the value to that type before validating it. + type: 'string', // optional, the type that the value should conform to + description: '' // optional, describes the option and is used when generating the command line help + } } } @@ -152,5 +173,3 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of 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. - -[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/mac-/opter/trend.png)](https://bitdeli.com/free "Bitdeli Badge") diff --git a/lib/opter.js b/lib/opter.js index c070bb7..14266e5 100644 --- a/lib/opter.js +++ b/lib/opter.js @@ -1,6 +1,11 @@ var commander = require('commander'), - path = require('object-path'), - fs = require('fs'); + objPath = require('object-path'), + path = require('path'), + fs = require('fs'), + ZSchema = require('z-schema'), + ZSchemaErrors = require('z-schema-errors'), + validator = new ZSchema(), + reporter = ZSchemaErrors.init(); /* example options object: @@ -21,7 +26,7 @@ var commander = require('commander'), } } */ -module.exports = function (options, appVersion) { +module.exports = function (options, appVersion, opterFileLocation) { if (!options || !appVersion) { throw new Error('Missing arguments'); } @@ -109,8 +114,9 @@ module.exports = function (options, appVersion) { for (optName in options) { if (options.hasOwnProperty(optName)) { option = options[optName]; - if (!option.argument && option.hasOwnProperty('type') && option.type !== Boolean) { - throw new Error('Please specify an "argument" property if declaring the "type" as anything other than Boolean'); + + if (option.hasOwnProperty('schema') && option.schema.type !== 'boolean') { + option.argument = option.schema.type || 'string'; } requiredText = (option.required) ? '(Required) ' : '(Optional) '; description = option.description || 'No Description.'; @@ -119,7 +125,7 @@ module.exports = function (options, appVersion) { description += ' Defaults to: '; description += (typeof(option.defaultValue) === 'string') ? '"' + option.defaultValue + '"' : option.defaultValue; } - longOptionStr = optName.replace(/([A-Z])/g, function (match) { return "-" + match.toLowerCase(); }); + longOptionStr = optName.replace(/([A-Z])/g, function (match) { return '-' + match.toLowerCase(); }); var argOpenChar = (option.required) ? '<' : '[', argCloseChar = (option.required) ? '>' : ']'; longOptionStr = (option.argument) ? longOptionStr + ' ' + argOpenChar + option.argument + argCloseChar : longOptionStr; @@ -146,7 +152,11 @@ module.exports = function (options, appVersion) { // look for opter.json as a sibling to the file currently being executed if (process.argv[1]) { - configFile = process.argv[1].substr(0, process.argv[1].lastIndexOf('/') + 1) + 'opter.json'; + var basePath = process.argv[1].substr(0, process.argv[1].lastIndexOf('/') + 1); + if (opterFileLocation) { + opterFileLocation = (opterFileLocation.indexOf(path.sep) === 0) ? opterFileLocation : basePath + opterFileLocation; + } + configFile = opterFileLocation || basePath + 'opter.json'; try { fs.statSync(configFile); configFile = require(configFile); @@ -162,55 +172,60 @@ module.exports = function (options, appVersion) { option = options[optName]; var value = commander[optName]; if (value === undefined) { - value = process.env[optName.replace(/\./g, '_')]; + value = process.env[optName.replace(/\./g, '_')] || process.env[optName.replace(/\./g, '_').toUpperCase()]; if (value === undefined) { - value = path.get(configFile, optName); + value = objPath.get(configFile, optName); if (value === undefined) { value = option.defaultValue; } } } - if (option.hasOwnProperty('type')) { - switch (option.type) { + if (option.hasOwnProperty('schema')) { + // if type is defined, try to convert the value to the specified type + if (option.schema.hasOwnProperty('type')) { + switch (option.schema.type) { - case Boolean: - value = (value === "true") || (value === true); - break; + case 'boolean': + value = (value === 'true') || (value === true); + break; - case Number: - // fastest, most reliable way to convert a string to a valid number - value = 1 * value; - break; + case 'number': + case 'integer': + // fastest, most reliable way to convert a string to a valid number + value = 1 * value; + break; - case Date: - // test string to see if it's an all-numeric value, and if so, parse it - value = (/^\d+$/.test(value)) ? 1 * value : value; - value = new Date(value); - break; + case 'object': + case 'array': + if (typeof value === 'string') { + try { + value = JSON.parse(value); + } catch (e) { + throw new Error('Option "' + optName + '" has a value that cannot be converted to an Object/Array: ' + value); + } + } else { + if (typeof value !== 'object') { + throw new Error('Option "' + optName + '" has a value is not an Object/Array: ' + value); + } + } + break; - case Object: - if (typeof value === 'string') { - try { - value = JSON.parse(value); - } catch (e) { - throw new Error('Option "' + optName + '" has a value that cannot be converted to an Object: ' + value); - } - } else { - if (typeof value !== 'object') { - throw new Error('Option "' + optName + '" has a value is not an Object: ' + value); - } + default: + value = (value !== null && value !== undefined) ? value.toString() : value; } - break; - - default: - value = (value !== null && value !== undefined) ? value.toString() : value; + } + // validate the value against the schema + var isValid = validator.validate(value, option.schema); + if (!isValid) { + var errorMsg = reporter.extractMessage(validator.lastReport); + throw new Error(errorMsg); } } if (value === undefined && option.required) { throw new Error('Option "' + optName + '" is not set and is required.'); } - path.set(config, optName, value); + objPath.set(config, optName, value); } } return config; diff --git a/package.json b/package.json index 8def324..a06dce8 100644 --- a/package.json +++ b/package.json @@ -4,18 +4,20 @@ "contributors": [ "Mac Angell " ], - "version": "0.7.0", + "version": "1.0.0", "dependencies": { "commander": "2.x.x", "underscore": "1.x.x", - "object-path": "0.x.x" + "object-path": "0.x.x", + "z-schema": "^3.0.1", + "z-schema-errors": "0.0.1" }, "devDependencies": { - "mocha": "1.x.x", - "jshint": "0.x.x", - "blanket": "1.0.x", - "travis-cov": "0.2.x", "rewire": "2.x.x", + "mocha": "1.x.x", + "jshint": "2.x.x", + "travis-cov": "0.x.x", + "blanket": "1.x.x", "coveralls": "2.x.x", "mocha-lcov-reporter": "0.x.x" }, @@ -31,15 +33,19 @@ "url": "https://github.com/mac-/opter" }, "scripts": { - "test": "make test && make test-cov && make test-lcov | ./node_modules/coveralls/bin/coveralls.js", + "test": "make test && make test-cov && make test-lcov | ./node_modules/coveralls/bin/coveralls.js" + }, + "config": { "blanket": { - "pattern": "//^((?!\/node_modules\/)(?!\/test\/).)*$/ig", + "pattern": "//^((?!/node_modules/)(?!/test/).)*$/ig", "onlyCwd": true, "data-cover-flags": { "branchTracking": true } }, - "travis-cov": { "threshold": 95 } + "travis-cov": { + "threshold": -1 + } }, "license": "MIT" } \ No newline at end of file diff --git a/test/jshint/config.json b/test/jshint/config.json index 9c40d56..a877983 100644 --- a/test/jshint/config.json +++ b/test/jshint/config.json @@ -1,73 +1,50 @@ { - // Settings - "passfail" : false, // Stop on first error. - "maxerr" : 100, // Maximum error before stopping. - - - // Predefined globals whom JSHint will ignore. - "browser" : false, // Standard browser globals e.g. `window`, `document`. - - "node" : true, - "rhino" : false, - "couch" : false, - "wsh" : false, // Windows Scripting Host. - - "jquery" : false, - "prototypejs" : false, - "mootools" : false, - "dojo" : false, - - "predef" : [ // Custom globals. - //"exampleVar", - //"anotherCoolGlobal", - //"iLoveDouglas" - ], - - - // Development. - "debug" : false, // Allow debugger statements e.g. browser breakpoints. - "devel" : true, // Allow developments statements e.g. `console.log();`. - - - // ECMAScript 5. - "es5" : true, // Allow ECMAScript 5 syntax. - "strict" : false, // Require `use strict` pragma in every file. - "globalstrict" : false, // Allow global "use strict" (also enables 'strict'). - - - // The Good Parts. - "asi" : false, // Tolerate Automatic Semicolon Insertion (no semicolons). - "laxbreak" : false, // Tolerate unsafe line breaks e.g. `return [\n] x` without semicolons. - "bitwise" : false, // Prohibit bitwise operators (&, |, ^, etc.). - "boss" : false, // Tolerate assignments inside if, for & while. Usually conditions & loops are for comparison, not assignments. - "curly" : true, // Require {} for every new block or scope. - "eqeqeq" : true, // Require triple equals i.e. `===`. - "eqnull" : false, // Tolerate use of `== null`. - "evil" : false, // Tolerate use of `eval`. - "expr" : false, // Tolerate `ExpressionStatement` as Programs. - "forin" : false, // Tolerate `for in` loops without `hasOwnPrototype`. - "immed" : true, // Require immediate invocations to be wrapped in parens e.g. `( function(){}() );` - "latedef" : true, // Prohibit variable use before definition. - "loopfunc" : true, // Allow functions to be defined within loops. - "noarg" : true, // Prohibit use of `arguments.caller` and `arguments.callee`. - "regexp" : false, // Prohibit `.` and `[^...]` in regular expressions. - "regexdash" : false, // Tolerate unescaped last dash i.e. `[-...]`. - "scripturl" : true, // Tolerate script-targeted URLs. - "shadow" : false, // Allows re-define variables later in code e.g. `var x=1; x=2;`. - "supernew" : false, // Tolerate `new function () { ... };` and `new Object;`. - "undef" : true, // Require all non-global variables be declared before they are used. - - - // Personal styling preferences. - "newcap" : true, // Require capitalization of all constructor functions e.g. `new F()`. - "noempty" : true, // Prohibit use of empty blocks. - "nonew" : true, // Prohibit use of constructors for side-effects. - "nomen" : false, // Prohibit use of initial or trailing underbars in names. - "onevar" : false, // Allow only one `var` statement per function. - "plusplus" : false, // Prohibit use of `++` & `--`. - "sub" : true, // Tolerate all forms of subscript notation besides dot notation e.g. `dict['key']` instead of `dict.key`. - "trailing" : true, // Prohibit trailing whitespaces. - "white" : false, // Check against strict whitespace and indentation rules. - "indent" : 4 // Specify indentation spacing -} - + "bitwise": false, + "camelcase": true, + "curly": true, + "eqeqeq": true, + "es3": false, + "forin": true, + "immed": true, + "indent": 0, + "latedef": true, + "newcap": false, + "noarg": false, + "noempty": true, + "nonew": false, + "plusplus": false, + "quotmark": "single", + "undef": true, + "unused": true, + "strict": false, + "trailing": true, + "maxparams": 0, + "maxdepth": 0, + "maxstatements": 0, + "maxcomplexity": 0, + "maxlen": 0, + + "asi": false, + "boss": true, + "debug": false, + "eqnull": true, + "esnext": false, + "evil": false, + "expr": false, + "funcscope": false, + "globalstrict": false, + "iterator": false, + "lastsemic": false, + "laxbreak": false, + "laxcomma": false, + "loopfunc": true, + "multistr": false, + "proto": false, + "smarttabs": false, + "shadow": false, + "sub": true, + "supernew": false, + "validthis": false, + + "node": true +} \ No newline at end of file diff --git a/test/opter.test.js b/test/opter.test.js index d7c86af..9bed16b 100644 --- a/test/opter.test.js +++ b/test/opter.test.js @@ -121,66 +121,66 @@ describe('Opter Unit Tests', function() { 'node', './test/opter.test.js', '--my-option-from-args1', '100', '--my-option-from-args2', 'true', - '--my-option-from-args3', '1234567890', - '--my-option-from-args4', '2013-07-26T23:07:22.882Z', - '--my-option-from-args5', '0' + '--my-option-from-args3', '0' ]); var cfg = opter({ myOptionFromArgs1: { defaultValue: '10', argument: 'number', - type: Number + schema: { + type: 'number' + } }, myOptionFromArgs2: { defaultValue: 'false', - type: Boolean + schema: { + type: 'boolean' + } }, myOptionFromArgs3: { - defaultValue: '9999', - argument: 'date', - type: Date - }, - myOptionFromArgs4: { - defaultValue: '9999', - argument: 'date', - type: Date - }, - myOptionFromArgs5: { defaultValue: '0', argument: 'string', - type: String + schema: { + type: 'string' + } }, - myOptionFromArgs6: { + myOptionFromArgs4: { defaultValue: '[]', - argument: 'object', - type: Object + argument: 'array', + schema: { + type: 'array' + } }, - myOptionFromArgs7: { + myOptionFromArgs5: { defaultValue: [], - argument: 'object', - type: Object + argument: 'array', + schema: { + type: 'array' + } }, - myOptionFromArgs8: { + myOptionFromArgs6: { defaultValue: '{}', argument: 'object', - type: Object + schema: { + type: 'object' + } }, - myOptionFromArgs9: { + myOptionFromArgs7: { defaultValue: {}, argument: 'object', - type: Object + schema: { + type: 'object' + } } }, '0.1.0'); assert.strictEqual(cfg.myOptionFromArgs1, 100, 'myOptionFromArgs1 is: 100'); assert.strictEqual(cfg.myOptionFromArgs2, true, 'myOptionFromArgs2 is: true'); - assert.strictEqual(cfg.myOptionFromArgs3.getTime(), 1234567890, 'myOptionFromArgs3 is a date with getTime of: 1234567890'); - assert.strictEqual(cfg.myOptionFromArgs4.getTime(), 1374880042882, 'myOptionFromArgs4 is a date with getTime of: 1374880042882'); - assert.strictEqual(cfg.myOptionFromArgs5, '0', 'myOptionFromArgs5 is : "0"'); - assert.strictEqual(cfg.myOptionFromArgs6 instanceof Array, true, 'expected value to be [], got: ' + JSON.stringify(cfg.myOptionFromArgs6)); - assert.strictEqual(cfg.myOptionFromArgs7 instanceof Array, true, 'expected value to be [], got: ' + JSON.stringify(cfg.myOptionFromArgs7)); - assert.strictEqual(cfg.myOptionFromArgs8 instanceof Object, true, 'expected value to be {}, got: ' + JSON.stringify(cfg.myOptionFromArgs8)); - assert.strictEqual(cfg.myOptionFromArgs9 instanceof Object, true, 'expected value to be {}, got: ' + JSON.stringify(cfg.myOptionFromArgs9)); + assert.strictEqual(cfg.myOptionFromArgs3, '0', 'myOptionFromArgs3 is : "0"'); + assert.strictEqual(cfg.myOptionFromArgs4 instanceof Array, true, 'expected value to be [], got: ' + JSON.stringify(cfg.myOptionFromArgs4)); + assert.strictEqual(cfg.myOptionFromArgs5 instanceof Array, true, 'expected value to be [], got: ' + JSON.stringify(cfg.myOptionFromArgs5)); + assert.strictEqual(cfg.myOptionFromArgs6 instanceof Object, true, 'expected value to be {}, got: ' + JSON.stringify(cfg.myOptionFromArgs6)); + assert.strictEqual(cfg.myOptionFromArgs7 instanceof Object, true, 'expected value to be {}, got: ' + JSON.stringify(cfg.myOptionFromArgs7)); done(); }); @@ -206,6 +206,28 @@ describe('Opter Unit Tests', function() { done(); }); + it('should read values from env as all caps', function(done) { + + setCommandLineArgsAndEnvVars(null, { + MYOPTIONFROMENV1: 'env1', + MYOPTIONFROMENV2: 'env2' + }); + + var cfg = opter({ + myOptionFromEnv1: { + defaultValue: 'default1', + argument: 'string' + }, + myOptionFromEnv2: { + defaultValue: 'default2', + argument: 'string' + } + }, '0.1.0'); + assert.strictEqual(cfg.myOptionFromEnv1, 'env1', 'MYOPTIONFROMENV1 is: env1'); + assert.strictEqual(cfg.myOptionFromEnv2, 'env2', 'MYOPTIONFROMENV2 is: env2'); + done(); + }); + it('should read values from default value', function(done) { setCommandLineArgsAndEnvVars(); @@ -313,45 +335,52 @@ describe('Opter Unit Tests', function() { done(); }); - it('should throw an error if an argument value is missing, and type is not Boolean', function(done) { + + it('should throw an error if an argument value is not an object string, and type is Object', function(done) { assert.throws(function() { var cfg = opter({ - optA: { - character: 'a', - required: true, - type: Number + myOptionFromArgs6: { + defaultValue: 'x', + argument: 'object', + schema: { + type: 'object' + } } }, '0.1.0'); - }, /.*? Please specify an/, 'throws error'); + }, /Option .*? has a value that cannot be converted to an Object\/Array: .*?/, 'throws error'); done(); }); - it('should throw an error if an argument value is not an object string, and type is Object', function(done) { + it('should throw an error if an argument value is not an object, and type is Object', function(done) { assert.throws(function() { var cfg = opter({ myOptionFromArgs6: { - defaultValue: 'x', + defaultValue: true, argument: 'object', - type: Object + schema: { + type: 'object' + } } }, '0.1.0'); - }, /Option .*? has a value that cannot be converted to an Object: .*?/, 'throws error'); + }, /Option .*? has a value is not an Object\/Array: .*?/, 'throws error'); done(); }); - it('should throw an error if an argument value is not an object, and type is Object', function(done) { + it('should throw an error if the value does not match the schema', function(done) { assert.throws(function() { var cfg = opter({ myOptionFromArgs6: { - defaultValue: true, - argument: 'object', - type: Object + defaultValue: 'fnord', + schema: { + type: 'string', + minLength: 10 + } } }, '0.1.0'); - }, /Option .*? has a value is not an Object: .*?/, 'throws error'); + }, 'throws error'); done(); }); @@ -361,7 +390,9 @@ describe('Opter Unit Tests', function() { myOptionFromArgs6: { defaultValue: [{"appName": "test"}], argument: 'object', - type: Object + schema: { + type: 'array' + } } }, '0.1.0'); done(); @@ -471,7 +502,26 @@ describe('Opter Unit Tests', function() { } }, '0.1.0'); assert.strictEqual(cfg.myOptionFromFile, 'fnord1', 'myOptionFromFile is: fnord1'); - assert.strictEqual(cfg.myOptionFromFile2, 'fnord2', 'myOptionFromEnv2 is: fnord2'); + assert.strictEqual(cfg.myOptionFromFile2, 'fnord2', 'myOptionFromFile2 is: fnord2'); + done(); + }); + + it('should read config from a specified file', function(done) { + + // change the location of the "running file" + setCommandLineArgsAndEnvVars(['node', __dirname + '/support/opter.test.js']); + var cfg = opter({ + myOptionFromDifferentFile: { + defaultValue: 'default1', + argument: 'string' + }, + myOptionFromDifferentFile2: { + defaultValue: 'default2', + argument: 'string' + } + }, '0.1.0', './other.json'); + assert.strictEqual(cfg.myOptionFromDifferentFile, 'fnord10', 'myOptionFromDifferentFile is: fnord10'); + assert.strictEqual(cfg.myOptionFromDifferentFile2, 'fnord20', 'myOptionFromDifferentFile2 is: fnord20'); done(); }); diff --git a/test/support/other.json b/test/support/other.json new file mode 100644 index 0000000..23bf010 --- /dev/null +++ b/test/support/other.json @@ -0,0 +1,4 @@ +{ + "myOptionFromDifferentFile": "fnord10", + "myOptionFromDifferentFile2": "fnord20" +} \ No newline at end of file