package/package.json000666 001750 001750 0000001703 12035253532013024 0ustar00000000 000000 { "name" : "optimist", "version" : "0.3.5", "description" : "Light-weight option parsing with an argv hash. No optstrings attached.", "main" : "./index.js", "directories" : { "lib" : ".", "test" : "test", "example" : "example" }, "dependencies" : { "wordwrap" : "~0.0.2" }, "devDependencies" : { "hashish": "~0.0.4", "tap" : "~0.2.4" }, "scripts" : { "test" : "tap ./test/*.js" }, "repository" : { "type" : "git", "url" : "http://github.com/substack/node-optimist.git" }, "keywords" : [ "argument", "args", "option", "parser", "parsing", "cli", "command" ], "author" : { "name" : "James Halliday", "email" : "mail@substack.net", "url" : "http://substack.net" }, "license" : "MIT/X11", "engine" : { "node" : ">=0.4" } } package/LICENSE000666 001750 001750 0000002165 11552420650011546 0ustar00000000 000000 Copyright 2010 James Halliday (mail@substack.net) This project is free software released under the MIT/X11 license: 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/x.js000666 001750 001750 0000000041 12002076367011340 0ustar00000000 000000 console.dir(require('./').argv); package/index.js000666 001750 001750 0000032557 12035253525012220 0ustar00000000 000000 var path = require('path'); var wordwrap = require('wordwrap'); /* Hack an instance of Argv with process.argv into Argv so people can do require('optimist')(['--beeble=1','-z','zizzle']).argv to parse a list of args and require('optimist').argv to get a parsed version of process.argv. */ var inst = Argv(process.argv.slice(2)); Object.keys(inst).forEach(function (key) { Argv[key] = typeof inst[key] == 'function' ? inst[key].bind(inst) : inst[key]; }); var exports = module.exports = Argv; function Argv (args, cwd) { var self = {}; if (!cwd) cwd = process.cwd(); self.$0 = process.argv .slice(0,2) .map(function (x) { var b = rebase(cwd, x); return x.match(/^\//) && b.length < x.length ? b : x }) .join(' ') ; if (process.argv[1] == process.env._) { self.$0 = process.env._.replace( path.dirname(process.execPath) + '/', '' ); } var flags = { bools : {}, strings : {} }; self.boolean = function (bools) { if (!Array.isArray(bools)) { bools = [].slice.call(arguments); } bools.forEach(function (name) { flags.bools[name] = true; }); return self; }; self.string = function (strings) { if (!Array.isArray(strings)) { strings = [].slice.call(arguments); } strings.forEach(function (name) { flags.strings[name] = true; }); return self; }; var aliases = {}; self.alias = function (x, y) { if (typeof x === 'object') { Object.keys(x).forEach(function (key) { self.alias(key, x[key]); }); } else if (Array.isArray(y)) { y.forEach(function (yy) { self.alias(x, yy); }); } else { var zs = (aliases[x] || []).concat(aliases[y] || []).concat(x, y); aliases[x] = zs.filter(function (z) { return z != x }); aliases[y] = zs.filter(function (z) { return z != y }); } return self; }; var demanded = {}; self.demand = function (keys) { if (typeof keys == 'number') { if (!demanded._) demanded._ = 0; demanded._ += keys; } else if (Array.isArray(keys)) { keys.forEach(function (key) { self.demand(key); }); } else { demanded[keys] = true; } return self; }; var usage; self.usage = function (msg, opts) { if (!opts && typeof msg === 'object') { opts = msg; msg = null; } usage = msg; if (opts) self.options(opts); return self; }; function fail (msg) { self.showHelp(); if (msg) console.error(msg); process.exit(1); } var checks = []; self.check = function (f) { checks.push(f); return self; }; var defaults = {}; self.default = function (key, value) { if (typeof key === 'object') { Object.keys(key).forEach(function (k) { self.default(k, key[k]); }); } else { defaults[key] = value; } return self; }; var descriptions = {}; self.describe = function (key, desc) { if (typeof key === 'object') { Object.keys(key).forEach(function (k) { self.describe(k, key[k]); }); } else { descriptions[key] = desc; } return self; }; self.parse = function (args) { return Argv(args).argv; }; self.option = self.options = function (key, opt) { if (typeof key === 'object') { Object.keys(key).forEach(function (k) { self.options(k, key[k]); }); } else { if (opt.alias) self.alias(key, opt.alias); if (opt.demand) self.demand(key); if (typeof opt.default !== 'undefined') { self.default(key, opt.default); } if (opt.boolean || opt.type === 'boolean') { self.boolean(key); } if (opt.string || opt.type === 'string') { self.string(key); } var desc = opt.describe || opt.description || opt.desc; if (desc) { self.describe(key, desc); } } return self; }; var wrap = null; self.wrap = function (cols) { wrap = cols; return self; }; self.showHelp = function (fn) { if (!fn) fn = console.error; fn(self.help()); }; self.help = function () { var keys = Object.keys( Object.keys(descriptions) .concat(Object.keys(demanded)) .concat(Object.keys(defaults)) .reduce(function (acc, key) { if (key !== '_') acc[key] = true; return acc; }, {}) ); var help = keys.length ? [ 'Options:' ] : []; if (usage) { help.unshift(usage.replace(/\$0/g, self.$0), ''); } var switches = keys.reduce(function (acc, key) { acc[key] = [ key ].concat(aliases[key] || []) .map(function (sw) { return (sw.length > 1 ? '--' : '-') + sw }) .join(', ') ; return acc; }, {}); var switchlen = longest(Object.keys(switches).map(function (s) { return switches[s] || ''; })); var desclen = longest(Object.keys(descriptions).map(function (d) { return descriptions[d] || ''; })); keys.forEach(function (key) { var kswitch = switches[key]; var desc = descriptions[key] || ''; if (wrap) { desc = wordwrap(switchlen + 4, wrap)(desc) .slice(switchlen + 4) ; } var spadding = new Array( Math.max(switchlen - kswitch.length + 3, 0) ).join(' '); var dpadding = new Array( Math.max(desclen - desc.length + 1, 0) ).join(' '); var type = null; if (flags.bools[key]) type = '[boolean]'; if (flags.strings[key]) type = '[string]'; if (!wrap && dpadding.length > 0) { desc += dpadding; } var prelude = ' ' + kswitch + spadding; var extra = [ type, demanded[key] ? '[required]' : null , defaults[key] !== undefined ? '[default: ' + JSON.stringify(defaults[key]) + ']' : null , ].filter(Boolean).join(' '); var body = [ desc, extra ].filter(Boolean).join(' '); if (wrap) { var dlines = desc.split('\n'); var dlen = dlines.slice(-1)[0].length + (dlines.length === 1 ? prelude.length : 0) body = desc + (dlen + extra.length > wrap - 2 ? '\n' + new Array(wrap - extra.length + 1).join(' ') + extra : new Array(wrap - extra.length - dlen + 1).join(' ') + extra ); } help.push(prelude + body); }); help.push(''); return help.join('\n'); }; Object.defineProperty(self, 'argv', { get : parseArgs, enumerable : true, }); function parseArgs () { var argv = { _ : [], $0 : self.$0 }; Object.keys(flags.bools).forEach(function (key) { setArg(key, defaults[key] || false); }); function setArg (key, val) { var num = Number(val); var value = typeof val !== 'string' || isNaN(num) ? val : num; if (flags.strings[key]) value = val; setKey(argv, key.split('.'), value); (aliases[key] || []).forEach(function (x) { argv[x] = argv[key]; }); } for (var i = 0; i < args.length; i++) { var arg = args[i]; if (arg === '--') { argv._.push.apply(argv._, args.slice(i + 1)); break; } else if (arg.match(/^--.+=/)) { var m = arg.match(/^--([^=]+)=(.*)/); setArg(m[1], m[2]); } else if (arg.match(/^--no-.+/)) { var key = arg.match(/^--no-(.+)/)[1]; setArg(key, false); } else if (arg.match(/^--.+/)) { var key = arg.match(/^--(.+)/)[1]; var next = args[i + 1]; if (next !== undefined && !next.match(/^-/) && !flags.bools[key] && (aliases[key] ? !flags.bools[aliases[key]] : true)) { setArg(key, next); i++; } else if (/^(true|false)$/.test(next)) { setArg(key, next === 'true'); i++; } else { setArg(key, true); } } else if (arg.match(/^-[^-]+/)) { var letters = arg.slice(1,-1).split(''); var broken = false; for (var j = 0; j < letters.length; j++) { if (letters[j+1] && letters[j+1].match(/\W/)) { setArg(letters[j], arg.slice(j+2)); broken = true; break; } else { setArg(letters[j], true); } } if (!broken) { var key = arg.slice(-1)[0]; if (args[i+1] && !args[i+1].match(/^-/) && !flags.bools[key] && (aliases[key] ? !flags.bools[aliases[key]] : true)) { setArg(key, args[i+1]); i++; } else if (args[i+1] && /true|false/.test(args[i+1])) { setArg(key, args[i+1] === 'true'); i++; } else { setArg(key, true); } } } else { var n = Number(arg); argv._.push(flags.strings['_'] || isNaN(n) ? arg : n); } } Object.keys(defaults).forEach(function (key) { if (!(key in argv)) { argv[key] = defaults[key]; if (key in aliases) { argv[aliases[key]] = defaults[key]; } } }); if (demanded._ && argv._.length < demanded._) { fail('Not enough non-option arguments: got ' + argv._.length + ', need at least ' + demanded._ ); } var missing = []; Object.keys(demanded).forEach(function (key) { if (!argv[key]) missing.push(key); }); if (missing.length) { fail('Missing required arguments: ' + missing.join(', ')); } checks.forEach(function (f) { try { if (f(argv) === false) { fail('Argument check failed: ' + f.toString()); } } catch (err) { fail(err) } }); return argv; } function longest (xs) { return Math.max.apply( null, xs.map(function (x) { return x.length }) ); } return self; }; // rebase an absolute path to a relative one with respect to a base directory // exported for tests exports.rebase = rebase; function rebase (base, dir) { var ds = path.normalize(dir).split('/').slice(1); var bs = path.normalize(base).split('/').slice(1); for (var i = 0; ds[i] && ds[i] == bs[i]; i++); ds.splice(0, i); bs.splice(0, i); var p = path.normalize( bs.map(function () { return '..' }).concat(ds).join('/') ).replace(/\/$/,'').replace(/^$/, '.'); return p.match(/^[.\/]/) ? p : './' + p; }; function setKey (obj, keys, value) { var o = obj; keys.slice(0,-1).forEach(function (key) { if (o[key] === undefined) o[key] = {}; o = o[key]; }); var key = keys[keys.length - 1]; if (o[key] === undefined || typeof o[key] === 'boolean') { o[key] = value; } else if (Array.isArray(o[key])) { o[key].push(value); } else { o[key] = [ o[key], value ]; } } package/example/line_count_options.js000666 001750 001750 0000001173 11747433346016456 0ustar00000000 000000 #!/usr/bin/env node var argv = require('optimist') .usage('Count the lines in a file.\nUsage: $0') .options({ file : { demand : true, alias : 'f', description : 'Load a file' }, base : { alias : 'b', description : 'Numeric base to use for output', default : 10, }, }) .argv ; var fs = require('fs'); var s = fs.createReadStream(argv.file); var lines = 0; s.on('data', function (buf) { lines += buf.toString().match(/\n/g).length; }); s.on('end', function () { console.log(lines.toString(argv.base)); }); package/example/boolean_double.js000666 001750 001750 0000000231 11747433346015507 0ustar00000000 000000 #!/usr/bin/env node var argv = require('optimist') .boolean(['x','y','z']) .argv ; console.dir([ argv.x, argv.y, argv.z ]); console.dir(argv._); package/example/divide.js000666 001750 001750 0000000237 11747433346014010 0ustar00000000 000000 #!/usr/bin/env node var argv = require('optimist') .usage('Usage: $0 -x [num] -y [num]') .demand(['x','y']) .argv; console.log(argv.x / argv.y); package/example/nonopt.js000666 001750 001750 0000000166 11747433346014062 0ustar00000000 000000 #!/usr/bin/env node var argv = require('optimist').argv; console.log('(%d,%d)', argv.x, argv.y); console.log(argv._); package/example/string.js000666 001750 001750 0000000331 11747433346014045 0ustar00000000 000000 #!/usr/bin/env node var argv = require('optimist') .string('x', 'y') .argv ; console.dir([ argv.x, argv.y ]); /* Turns off numeric coercion: ./node string.js -x 000123 -y 9876 [ '000123', '9876' ] */ package/example/default_hash.js000666 001750 001750 0000000200 11747433346015161 0ustar00000000 000000 #!/usr/bin/env node var argv = require('optimist') .default({ x : 10, y : 10 }) .argv ; console.log(argv.x + argv.y); package/example/reflect.js000666 001750 001750 0000000073 11552420650014152 0ustar00000000 000000 #!/usr/bin/env node console.dir(require('optimist').argv); package/example/default_singles.js000666 001750 001750 0000000211 11747433346015704 0ustar00000000 000000 #!/usr/bin/env node var argv = require('optimist') .default('x', 10) .default('y', 10) .argv ; console.log(argv.x + argv.y); package/example/usage-options.js000666 001750 001750 0000000670 11747433346015342 0ustar00000000 000000 var optimist = require('./../index'); var argv = optimist.usage('This is my awesome program', { 'about': { description: 'Provide some details about the author of this program', required: true, short: 'a', }, 'info': { description: 'Provide some information about the node.js agains!!!!!!', boolean: true, short: 'i' } }).argv; optimist.showHelp(); console.log('\n\nInspecting options'); console.dir(argv);package/example/bool.js000666 001750 001750 0000000353 11747433346013476 0ustar00000000 000000 #!/usr/bin/env node var util = require('util'); var argv = require('optimist').argv; if (argv.s) { util.print(argv.fr ? 'Le chat dit: ' : 'The cat says: '); } console.log( (argv.fr ? 'miaou' : 'meow') + (argv.p ? '.' : '') ); package/example/short.js000666 001750 001750 0000000141 11747433346013675 0ustar00000000 000000 #!/usr/bin/env node var argv = require('optimist').argv; console.log('(%d,%d)', argv.x, argv.y); package/example/xup.js000666 001750 001750 0000000301 11747433346013350 0ustar00000000 000000 #!/usr/bin/env node var argv = require('optimist').argv; if (argv.rif - 5 * argv.xup > 7.138) { console.log('Buy more riffiwobbles'); } else { console.log('Sell the xupptumblers'); } package/example/boolean_single.js000666 001750 001750 0000000173 11747433346015523 0ustar00000000 000000 #!/usr/bin/env node var argv = require('optimist') .boolean('v') .argv ; console.dir(argv.v); console.dir(argv._); package/example/line_count_wrap.js000666 001750 001750 0000001367 11747433346015741 0ustar00000000 000000 #!/usr/bin/env node var argv = require('optimist') .usage('Count the lines in a file.\nUsage: $0') .wrap(80) .demand('f') .alias('f', [ 'file', 'filename' ]) .describe('f', "Load a file. It's pretty important." + " Required even. So you'd better specify it." ) .alias('b', 'base') .describe('b', 'Numeric base to display the number of lines in') .default('b', 10) .describe('x', 'Super-secret optional parameter which is secret') .default('x', '') .argv ; var fs = require('fs'); var s = fs.createReadStream(argv.file); var lines = 0; s.on('data', function (buf) { lines += buf.toString().match(/\n/g).length; }); s.on('end', function () { console.log(lines.toString(argv.base)); }); package/example/line_count.js000666 001750 001750 0000000631 11747433346014701 0ustar00000000 000000 #!/usr/bin/env node var argv = require('optimist') .usage('Count the lines in a file.\nUsage: $0') .demand('f') .alias('f', 'file') .describe('f', 'Load a file') .argv ; var fs = require('fs'); var s = fs.createReadStream(argv.file); var lines = 0; s.on('data', function (buf) { lines += buf.toString().match(/\n/g).length; }); s.on('end', function () { console.log(lines); }); package/test/parse.js000666 001750 001750 0000023643 12035253525013176 0ustar00000000 000000 var optimist = require('../index'); var path = require('path'); var test = require('tap').test; var $0 = 'node ./' + path.relative(process.cwd(), __filename); test('short boolean', function (t) { var parse = optimist.parse([ '-b' ]); t.same(parse, { b : true, _ : [], $0 : $0 }); t.same(typeof parse.b, 'boolean'); t.end(); }); test('long boolean', function (t) { t.same( optimist.parse([ '--bool' ]), { bool : true, _ : [], $0 : $0 } ); t.end(); }); test('bare', function (t) { t.same( optimist.parse([ 'foo', 'bar', 'baz' ]), { _ : [ 'foo', 'bar', 'baz' ], $0 : $0 } ); t.end(); }); test('short group', function (t) { t.same( optimist.parse([ '-cats' ]), { c : true, a : true, t : true, s : true, _ : [], $0 : $0 } ); t.end(); }); test('short group next', function (t) { t.same( optimist.parse([ '-cats', 'meow' ]), { c : true, a : true, t : true, s : 'meow', _ : [], $0 : $0 } ); t.end(); }); test('short capture', function (t) { t.same( optimist.parse([ '-h', 'localhost' ]), { h : 'localhost', _ : [], $0 : $0 } ); t.end(); }); test('short captures', function (t) { t.same( optimist.parse([ '-h', 'localhost', '-p', '555' ]), { h : 'localhost', p : 555, _ : [], $0 : $0 } ); t.end(); }); test('long capture sp', function (t) { t.same( optimist.parse([ '--pow', 'xixxle' ]), { pow : 'xixxle', _ : [], $0 : $0 } ); t.end(); }); test('long capture eq', function (t) { t.same( optimist.parse([ '--pow=xixxle' ]), { pow : 'xixxle', _ : [], $0 : $0 } ); t.end() }); test('long captures sp', function (t) { t.same( optimist.parse([ '--host', 'localhost', '--port', '555' ]), { host : 'localhost', port : 555, _ : [], $0 : $0 } ); t.end(); }); test('long captures eq', function (t) { t.same( optimist.parse([ '--host=localhost', '--port=555' ]), { host : 'localhost', port : 555, _ : [], $0 : $0 } ); t.end(); }); test('mixed short bool and capture', function (t) { t.same( optimist.parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), { f : true, p : 555, h : 'localhost', _ : [ 'script.js' ], $0 : $0, } ); t.end(); }); test('short and long', function (t) { t.same( optimist.parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), { f : true, p : 555, h : 'localhost', _ : [ 'script.js' ], $0 : $0, } ); t.end(); }); test('no', function (t) { t.same( optimist.parse([ '--no-moo' ]), { moo : false, _ : [], $0 : $0 } ); t.end(); }); test('multi', function (t) { t.same( optimist.parse([ '-v', 'a', '-v', 'b', '-v', 'c' ]), { v : ['a','b','c'], _ : [], $0 : $0 } ); t.end(); }); test('comprehensive', function (t) { t.same( optimist.parse([ '--name=meowmers', 'bare', '-cats', 'woo', '-h', 'awesome', '--multi=quux', '--key', 'value', '-b', '--bool', '--no-meep', '--multi=baz', '--', '--not-a-flag', 'eek' ]), { c : true, a : true, t : true, s : 'woo', h : 'awesome', b : true, bool : true, key : 'value', multi : [ 'quux', 'baz' ], meep : false, name : 'meowmers', _ : [ 'bare', '--not-a-flag', 'eek' ], $0 : $0 } ); t.end(); }); test('nums', function (t) { var argv = optimist.parse([ '-x', '1234', '-y', '5.67', '-z', '1e7', '-w', '10f', '--hex', '0xdeadbeef', '789', ]); t.same(argv, { x : 1234, y : 5.67, z : 1e7, w : '10f', hex : 0xdeadbeef, _ : [ 789 ], $0 : $0 }); t.same(typeof argv.x, 'number'); t.same(typeof argv.y, 'number'); t.same(typeof argv.z, 'number'); t.same(typeof argv.w, 'string'); t.same(typeof argv.hex, 'number'); t.same(typeof argv._[0], 'number'); t.end(); }); test('flag boolean', function (t) { var parse = optimist([ '-t', 'moo' ]).boolean(['t']).argv; t.same(parse, { t : true, _ : [ 'moo' ], $0 : $0 }); t.same(typeof parse.t, 'boolean'); t.end(); }); test('flag boolean value', function (t) { var parse = optimist(['--verbose', 'false', 'moo', '-t', 'true']) .boolean(['t', 'verbose']).default('verbose', true).argv; t.same(parse, { verbose: false, t: true, _: ['moo'], $0 : $0 }); t.same(typeof parse.verbose, 'boolean'); t.same(typeof parse.t, 'boolean'); t.end(); }); test('flag boolean default false', function (t) { var parse = optimist(['moo']) .boolean(['t', 'verbose']) .default('verbose', false) .default('t', false).argv; t.same(parse, { verbose: false, t: false, _: ['moo'], $0 : $0 }); t.same(typeof parse.verbose, 'boolean'); t.same(typeof parse.t, 'boolean'); t.end(); }); test('boolean groups', function (t) { var parse = optimist([ '-x', '-z', 'one', 'two', 'three' ]) .boolean(['x','y','z']).argv; t.same(parse, { x : true, y : false, z : true, _ : [ 'one', 'two', 'three' ], $0 : $0 }); t.same(typeof parse.x, 'boolean'); t.same(typeof parse.y, 'boolean'); t.same(typeof parse.z, 'boolean'); t.end(); }); test('strings' , function (t) { var s = optimist([ '-s', '0001234' ]).string('s').argv.s; t.same(s, '0001234'); t.same(typeof s, 'string'); var x = optimist([ '-x', '56' ]).string('x').argv.x; t.same(x, '56'); t.same(typeof x, 'string'); t.end(); }); test('stringArgs', function (t) { var s = optimist([ ' ', ' ' ]).string('_').argv._; t.same(s.length, 2); t.same(typeof s[0], 'string'); t.same(s[0], ' '); t.same(typeof s[1], 'string'); t.same(s[1], ' '); t.end(); }); test('slashBreak', function (t) { t.same( optimist.parse([ '-I/foo/bar/baz' ]), { I : '/foo/bar/baz', _ : [], $0 : $0 } ); t.same( optimist.parse([ '-xyz/foo/bar/baz' ]), { x : true, y : true, z : '/foo/bar/baz', _ : [], $0 : $0 } ); t.end(); }); test('alias', function (t) { var argv = optimist([ '-f', '11', '--zoom', '55' ]) .alias('z', 'zoom') .argv ; t.equal(argv.zoom, 55); t.equal(argv.z, argv.zoom); t.equal(argv.f, 11); t.end(); }); test('multiAlias', function (t) { var argv = optimist([ '-f', '11', '--zoom', '55' ]) .alias('z', [ 'zm', 'zoom' ]) .argv ; t.equal(argv.zoom, 55); t.equal(argv.z, argv.zoom); t.equal(argv.z, argv.zm); t.equal(argv.f, 11); t.end(); }); test('boolean default true', function (t) { var argv = optimist.options({ sometrue: { boolean: true, default: true } }).argv; t.equal(argv.sometrue, true); t.end(); }); test('boolean default false', function (t) { var argv = optimist.options({ somefalse: { boolean: true, default: false } }).argv; t.equal(argv.somefalse, false); t.end(); }); test('nested dotted objects', function (t) { var argv = optimist([ '--foo.bar', '3', '--foo.baz', '4', '--foo.quux.quibble', '5', '--foo.quux.o_O', '--beep.boop' ]).argv; t.same(argv.foo, { bar : 3, baz : 4, quux : { quibble : 5, o_O : true }, }); t.same(argv.beep, { boop : true }); t.end(); }); test('boolean and alias with chainable api', function (t) { var aliased = [ '-h', 'derp' ]; var regular = [ '--herp', 'derp' ]; var opts = { herp: { alias: 'h', boolean: true } }; var aliasedArgv = optimist(aliased) .boolean('herp') .alias('h', 'herp') .argv; var propertyArgv = optimist(regular) .boolean('herp') .alias('h', 'herp') .argv; var expected = { herp: true, h: true, '_': [ 'derp' ], '$0': $0, }; t.same(aliasedArgv, expected); t.same(propertyArgv, expected); t.end(); }); test('boolean and alias with options hash', function (t) { var aliased = [ '-h', 'derp' ]; var regular = [ '--herp', 'derp' ]; var opts = { herp: { alias: 'h', boolean: true } }; var aliasedArgv = optimist(aliased) .options(opts) .argv; var propertyArgv = optimist(regular).options(opts).argv; var expected = { herp: true, h: true, '_': [ 'derp' ], '$0': $0, }; t.same(aliasedArgv, expected); t.same(propertyArgv, expected); t.end(); }); test('boolean and alias using explicit true', function (t) { var aliased = [ '-h', 'true' ]; var regular = [ '--herp', 'true' ]; var opts = { herp: { alias: 'h', boolean: true } }; var aliasedArgv = optimist(aliased) .boolean('h') .alias('h', 'herp') .argv; var propertyArgv = optimist(regular) .boolean('h') .alias('h', 'herp') .argv; var expected = { herp: true, h: true, '_': [ ], '$0': $0, }; t.same(aliasedArgv, expected); t.same(propertyArgv, expected); t.end(); }); // regression, see https://github.com/substack/node-optimist/issues/71 test('boolean and --x=true', function(t) { var parsed = optimist(['--boool', '--other=true']).boolean('boool').argv; t.same(parsed.boool, true); t.same(parsed.other, 'true'); parsed = optimist(['--boool', '--other=false']).boolean('boool').argv; t.same(parsed.boool, true); t.same(parsed.other, 'false'); t.end(); }); package/test/_.js000666 001750 001750 0000003327 11741635417012306 0ustar00000000 000000 var spawn = require('child_process').spawn; var test = require('tap').test; test('dotSlashEmpty', testCmd('./bin.js', [])); test('dotSlashArgs', testCmd('./bin.js', [ 'a', 'b', 'c' ])); test('nodeEmpty', testCmd('node bin.js', [])); test('nodeArgs', testCmd('node bin.js', [ 'x', 'y', 'z' ])); test('whichNodeEmpty', function (t) { var which = spawn('which', ['node']); which.stdout.on('data', function (buf) { t.test( testCmd(buf.toString().trim() + ' bin.js', []) ); t.end(); }); which.stderr.on('data', function (err) { assert.error(err); t.end(); }); }); test('whichNodeArgs', function (t) { var which = spawn('which', ['node']); which.stdout.on('data', function (buf) { t.test( testCmd(buf.toString().trim() + ' bin.js', [ 'q', 'r' ]) ); t.end(); }); which.stderr.on('data', function (err) { t.error(err); t.end(); }); }); function testCmd (cmd, args) { return function (t) { var to = setTimeout(function () { assert.fail('Never got stdout data.') }, 5000); var oldDir = process.cwd(); process.chdir(__dirname + '/_'); var cmds = cmd.split(' '); var bin = spawn(cmds[0], cmds.slice(1).concat(args.map(String))); process.chdir(oldDir); bin.stderr.on('data', function (err) { t.error(err); t.end(); }); bin.stdout.on('data', function (buf) { clearTimeout(to); var _ = JSON.parse(buf.toString()); t.same(_.map(String), args.map(String)); t.end(); }); }; } package/test/usage.js000666 001750 001750 0000015205 11747432431013167 0ustar00000000 000000 var Hash = require('hashish'); var optimist = require('../index'); var test = require('tap').test; test('usageFail', function (t) { var r = checkUsage(function () { return optimist('-x 10 -z 20'.split(' ')) .usage('Usage: $0 -x NUM -y NUM') .demand(['x','y']) .argv; }); t.same( r.result, { x : 10, z : 20, _ : [], $0 : './usage' } ); t.same( r.errors.join('\n').split(/\n+/), [ 'Usage: ./usage -x NUM -y NUM', 'Options:', ' -x [required]', ' -y [required]', 'Missing required arguments: y', ] ); t.same(r.logs, []); t.ok(r.exit); t.end(); }); test('usagePass', function (t) { var r = checkUsage(function () { return optimist('-x 10 -y 20'.split(' ')) .usage('Usage: $0 -x NUM -y NUM') .demand(['x','y']) .argv; }); t.same(r, { result : { x : 10, y : 20, _ : [], $0 : './usage' }, errors : [], logs : [], exit : false, }); t.end(); }); test('checkPass', function (t) { var r = checkUsage(function () { return optimist('-x 10 -y 20'.split(' ')) .usage('Usage: $0 -x NUM -y NUM') .check(function (argv) { if (!('x' in argv)) throw 'You forgot about -x'; if (!('y' in argv)) throw 'You forgot about -y'; }) .argv; }); t.same(r, { result : { x : 10, y : 20, _ : [], $0 : './usage' }, errors : [], logs : [], exit : false, }); t.end(); }); test('checkFail', function (t) { var r = checkUsage(function () { return optimist('-x 10 -z 20'.split(' ')) .usage('Usage: $0 -x NUM -y NUM') .check(function (argv) { if (!('x' in argv)) throw 'You forgot about -x'; if (!('y' in argv)) throw 'You forgot about -y'; }) .argv; }); t.same( r.result, { x : 10, z : 20, _ : [], $0 : './usage' } ); t.same( r.errors.join('\n').split(/\n+/), [ 'Usage: ./usage -x NUM -y NUM', 'You forgot about -y' ] ); t.same(r.logs, []); t.ok(r.exit); t.end(); }); test('checkCondPass', function (t) { function checker (argv) { return 'x' in argv && 'y' in argv; } var r = checkUsage(function () { return optimist('-x 10 -y 20'.split(' ')) .usage('Usage: $0 -x NUM -y NUM') .check(checker) .argv; }); t.same(r, { result : { x : 10, y : 20, _ : [], $0 : './usage' }, errors : [], logs : [], exit : false, }); t.end(); }); test('checkCondFail', function (t) { function checker (argv) { return 'x' in argv && 'y' in argv; } var r = checkUsage(function () { return optimist('-x 10 -z 20'.split(' ')) .usage('Usage: $0 -x NUM -y NUM') .check(checker) .argv; }); t.same( r.result, { x : 10, z : 20, _ : [], $0 : './usage' } ); t.same( r.errors.join('\n').split(/\n+/).join('\n'), 'Usage: ./usage -x NUM -y NUM\n' + 'Argument check failed: ' + checker.toString() ); t.same(r.logs, []); t.ok(r.exit); t.end(); }); test('countPass', function (t) { var r = checkUsage(function () { return optimist('1 2 3 --moo'.split(' ')) .usage('Usage: $0 [x] [y] [z] {OPTIONS}') .demand(3) .argv; }); t.same(r, { result : { _ : [ '1', '2', '3' ], moo : true, $0 : './usage' }, errors : [], logs : [], exit : false, }); t.end(); }); test('countFail', function (t) { var r = checkUsage(function () { return optimist('1 2 --moo'.split(' ')) .usage('Usage: $0 [x] [y] [z] {OPTIONS}') .demand(3) .argv; }); t.same( r.result, { _ : [ '1', '2' ], moo : true, $0 : './usage' } ); t.same( r.errors.join('\n').split(/\n+/), [ 'Usage: ./usage [x] [y] [z] {OPTIONS}', 'Not enough non-option arguments: got 2, need at least 3', ] ); t.same(r.logs, []); t.ok(r.exit); t.end(); }); test('defaultSingles', function (t) { var r = checkUsage(function () { return optimist('--foo 50 --baz 70 --powsy'.split(' ')) .default('foo', 5) .default('bar', 6) .default('baz', 7) .argv ; }); t.same(r.result, { foo : '50', bar : 6, baz : '70', powsy : true, _ : [], $0 : './usage', }); t.end(); }); test('defaultAliases', function (t) { var r = checkUsage(function () { return optimist('') .alias('f', 'foo') .default('f', 5) .argv ; }); t.same(r.result, { f : '5', foo : '5', _ : [], $0 : './usage', }); t.end(); }); test('defaultHash', function (t) { var r = checkUsage(function () { return optimist('--foo 50 --baz 70'.split(' ')) .default({ foo : 10, bar : 20, quux : 30 }) .argv ; }); t.same(r.result, { _ : [], $0 : './usage', foo : 50, baz : 70, bar : 20, quux : 30, }); t.end(); }); test('rebase', function (t) { t.equal( optimist.rebase('/home/substack', '/home/substack/foo/bar/baz'), './foo/bar/baz' ); t.equal( optimist.rebase('/home/substack/foo/bar/baz', '/home/substack'), '../../..' ); t.equal( optimist.rebase('/home/substack/foo', '/home/substack/pow/zoom.txt'), '../pow/zoom.txt' ); t.end(); }); function checkUsage (f) { var exit = false; process._exit = process.exit; process._env = process.env; process._argv = process.argv; process.exit = function (t) { exit = true }; process.env = Hash.merge(process.env, { _ : 'node' }); process.argv = [ './usage' ]; var errors = []; var logs = []; console._error = console.error; console.error = function (msg) { errors.push(msg) }; console._log = console.log; console.log = function (msg) { logs.push(msg) }; var result = f(); process.exit = process._exit; process.env = process._env; process.argv = process._argv; console.error = console._error; console.log = console._log; return { errors : errors, logs : logs, exit : exit, result : result, }; }; package/test/_/bin.js000777 001750 001750 0000000140 11575305477013054 0ustar00000000 000000 #!/usr/bin/env node var argv = require('../../index').argv console.log(JSON.stringify(argv._)); package/test/_/argv.js000666 001750 001750 0000000077 11552420656013241 0ustar00000000 000000 #!/usr/bin/env node console.log(JSON.stringify(process.argv)); package/.travis.yml000666 001750 001750 0000000053 12035253562012647 0ustar00000000 000000 language: node_js node_js: - 0.6 - 0.8 package/README.markdown000666 001750 001750 0000023454 11741635417013257 0ustar00000000 000000 optimist ======== Optimist is a node.js library for option parsing for people who hate option parsing. More specifically, this module is for people who like all the --bells and -whistlz of program usage but think optstrings are a waste of time. With optimist, option parsing doesn't have to suck (as much). [![build status](https://secure.travis-ci.org/substack/node-optimist.png)](http://travis-ci.org/substack/node-optimist) examples ======== With Optimist, the options are just a hash! No optstrings attached. ------------------------------------------------------------------- xup.js: ````javascript #!/usr/bin/env node var argv = require('optimist').argv; if (argv.rif - 5 * argv.xup > 7.138) { console.log('Buy more riffiwobbles'); } else { console.log('Sell the xupptumblers'); } ```` *** $ ./xup.js --rif=55 --xup=9.52 Buy more riffiwobbles $ ./xup.js --rif 12 --xup 8.1 Sell the xupptumblers ![This one's optimistic.](http://substack.net/images/optimistic.png) But wait! There's more! You can do short options: ------------------------------------------------- short.js: ````javascript #!/usr/bin/env node var argv = require('optimist').argv; console.log('(%d,%d)', argv.x, argv.y); ```` *** $ ./short.js -x 10 -y 21 (10,21) And booleans, both long and short (and grouped): ---------------------------------- bool.js: ````javascript #!/usr/bin/env node var util = require('util'); var argv = require('optimist').argv; if (argv.s) { util.print(argv.fr ? 'Le chat dit: ' : 'The cat says: '); } console.log( (argv.fr ? 'miaou' : 'meow') + (argv.p ? '.' : '') ); ```` *** $ ./bool.js -s The cat says: meow $ ./bool.js -sp The cat says: meow. $ ./bool.js -sp --fr Le chat dit: miaou. And non-hypenated options too! Just use `argv._`! ------------------------------------------------- nonopt.js: ````javascript #!/usr/bin/env node var argv = require('optimist').argv; console.log('(%d,%d)', argv.x, argv.y); console.log(argv._); ```` *** $ ./nonopt.js -x 6.82 -y 3.35 moo (6.82,3.35) [ 'moo' ] $ ./nonopt.js foo -x 0.54 bar -y 1.12 baz (0.54,1.12) [ 'foo', 'bar', 'baz' ] Plus, Optimist comes with .usage() and .demand()! ------------------------------------------------- divide.js: ````javascript #!/usr/bin/env node var argv = require('optimist') .usage('Usage: $0 -x [num] -y [num]') .demand(['x','y']) .argv; console.log(argv.x / argv.y); ```` *** $ ./divide.js -x 55 -y 11 5 $ node ./divide.js -x 4.91 -z 2.51 Usage: node ./divide.js -x [num] -y [num] Options: -x [required] -y [required] Missing required arguments: y EVEN MORE HOLY COW ------------------ default_singles.js: ````javascript #!/usr/bin/env node var argv = require('optimist') .default('x', 10) .default('y', 10) .argv ; console.log(argv.x + argv.y); ```` *** $ ./default_singles.js -x 5 15 default_hash.js: ````javascript #!/usr/bin/env node var argv = require('optimist') .default({ x : 10, y : 10 }) .argv ; console.log(argv.x + argv.y); ```` *** $ ./default_hash.js -y 7 17 And if you really want to get all descriptive about it... --------------------------------------------------------- boolean_single.js ````javascript #!/usr/bin/env node var argv = require('optimist') .boolean('v') .argv ; console.dir(argv); ```` *** $ ./boolean_single.js -v foo bar baz true [ 'bar', 'baz', 'foo' ] boolean_double.js ````javascript #!/usr/bin/env node var argv = require('optimist') .boolean(['x','y','z']) .argv ; console.dir([ argv.x, argv.y, argv.z ]); console.dir(argv._); ```` *** $ ./boolean_double.js -x -z one two three [ true, false, true ] [ 'one', 'two', 'three' ] Optimist is here to help... --------------------------- You can describe parameters for help messages and set aliases. Optimist figures out how to format a handy help string automatically. line_count.js ````javascript #!/usr/bin/env node var argv = require('optimist') .usage('Count the lines in a file.\nUsage: $0') .demand('f') .alias('f', 'file') .describe('f', 'Load a file') .argv ; var fs = require('fs'); var s = fs.createReadStream(argv.file); var lines = 0; s.on('data', function (buf) { lines += buf.toString().match(/\n/g).length; }); s.on('end', function () { console.log(lines); }); ```` *** $ node line_count.js Count the lines in a file. Usage: node ./line_count.js Options: -f, --file Load a file [required] Missing required arguments: f $ node line_count.js --file line_count.js 20 $ node line_count.js -f line_count.js 20 methods ======= By itself, ````javascript require('optimist').argv ````` will use `process.argv` array to construct the `argv` object. You can pass in the `process.argv` yourself: ````javascript require('optimist')([ '-x', '1', '-y', '2' ]).argv ```` or use .parse() to do the same thing: ````javascript require('optimist').parse([ '-x', '1', '-y', '2' ]) ```` The rest of these methods below come in just before the terminating `.argv`. .alias(key, alias) ------------------ Set key names as equivalent such that updates to a key will propagate to aliases and vice-versa. Optionally `.alias()` can take an object that maps keys to aliases. .default(key, value) -------------------- Set `argv[key]` to `value` if no option was specified on `process.argv`. Optionally `.default()` can take an object that maps keys to default values. .demand(key) ------------ If `key` is a string, show the usage information and exit if `key` wasn't specified in `process.argv`. If `key` is a number, demand at least as many non-option arguments, which show up in `argv._`. If `key` is an Array, demand each element. .describe(key, desc) -------------------- Describe a `key` for the generated usage information. Optionally `.describe()` can take an object that maps keys to descriptions. .options(key, opt) ------------------ Instead of chaining together `.alias().demand().default()`, you can specify keys in `opt` for each of the chainable methods. For example: ````javascript var argv = require('optimist') .options('f', { alias : 'file', default : '/etc/passwd', }) .argv ; ```` is the same as ````javascript var argv = require('optimist') .alias('f', 'file') .default('f', '/etc/passwd') .argv ; ```` Optionally `.options()` can take an object that maps keys to `opt` parameters. .usage(message) --------------- Set a usage message to show which commands to use. Inside `message`, the string `$0` will get interpolated to the current script name or node command for the present script similar to how `$0` works in bash or perl. .check(fn) ---------- Check that certain conditions are met in the provided arguments. If `fn` throws or returns `false`, show the thrown error, usage information, and exit. .boolean(key) ------------- Interpret `key` as a boolean. If a non-flag option follows `key` in `process.argv`, that string won't get set as the value of `key`. If `key` never shows up as a flag in `process.arguments`, `argv[key]` will be `false`. If `key` is an Array, interpret all the elements as booleans. .string(key) ------------ Tell the parser logic not to interpret `key` as a number or boolean. This can be useful if you need to preserve leading zeros in an input. If `key` is an Array, interpret all the elements as strings. .wrap(columns) -------------- Format usage output to wrap at `columns` many columns. .help() ------- Return the generated usage string. .showHelp(fn=console.error) --------------------------- Print the usage data using `fn` for printing. .parse(args) ------------ Parse `args` instead of `process.argv`. Returns the `argv` object. .argv ----- Get the arguments as a plain old object. Arguments without a corresponding flag show up in the `argv._` array. The script name or node command is available at `argv.$0` similarly to how `$0` works in bash or perl. parsing tricks ============== stop parsing ------------ Use `--` to stop parsing flags and stuff the remainder into `argv._`. $ node examples/reflect.js -a 1 -b 2 -- -c 3 -d 4 { _: [ '-c', '3', '-d', '4' ], '$0': 'node ./examples/reflect.js', a: 1, b: 2 } negate fields ------------- If you want to explicity set a field to false instead of just leaving it undefined or to override a default you can do `--no-key`. $ node examples/reflect.js -a --no-b { _: [], '$0': 'node ./examples/reflect.js', a: true, b: false } numbers ------- Every argument that looks like a number (`!isNaN(Number(arg))`) is converted to one. This way you can just `net.createConnection(argv.port)` and you can add numbers out of `argv` with `+` without having that mean concatenation, which is super frustrating. duplicates ---------- If you specify a flag multiple times it will get turned into an array containing all the values in order. $ node examples/reflect.js -x 5 -x 8 -x 0 { _: [], '$0': 'node ./examples/reflect.js', x: [ 5, 8, 0 ] } dot notation ------------ When you use dots (`.`s) in argument names, an implicit object path is assumed. This lets you organize arguments into nested objects. $ node examples/reflect.js --foo.bar.baz=33 --foo.quux=5 { _: [], '$0': 'node ./examples/reflect.js', foo: { bar: { baz: 33 }, quux: 5 } } installation ============ With [npm](http://github.com/isaacs/npm), just do: npm install optimist or clone this project on github: git clone http://github.com/substack/node-optimist.git To run the tests with [expresso](http://github.com/visionmedia/expresso), just do: expresso inspired By =========== This module is loosely inspired by Perl's [Getopt::Casual](http://search.cpan.org/~photo/Getopt-Casual-0.13.1/Casual.pm).