Skip to content

Commit

Permalink
adding schema validation - fixes #3, adding ability to specify a diff…
Browse files Browse the repository at this point in the history
…erent config file - fixes #2, and mapping vars to environment in app caps as well - fixes #5
  • Loading branch information
mac- committed Dec 16, 2014
1 parent 947e53f commit 5743f51
Show file tree
Hide file tree
Showing 7 changed files with 250 additions and 182 deletions.
5 changes: 1 addition & 4 deletions 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
Expand Down
35 changes: 27 additions & 8 deletions README.md
Expand Up @@ -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
Expand All @@ -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
}
}
}

Expand Down Expand Up @@ -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")
93 changes: 54 additions & 39 deletions 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:
Expand All @@ -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');
}
Expand Down Expand Up @@ -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.';
Expand All @@ -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;
Expand All @@ -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);
Expand All @@ -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;
Expand Down
24 changes: 15 additions & 9 deletions package.json
Expand Up @@ -4,18 +4,20 @@
"contributors": [
"Mac Angell <mac.ang311@gmail.com>"
],
"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"
},
Expand All @@ -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"
}
121 changes: 49 additions & 72 deletions 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
}

0 comments on commit 5743f51

Please sign in to comment.