pax_global_header00006660000000000000000000000064122744556740014532gustar00rootroot0000000000000052 comment=27d131a72b3c7d8583fca9ab970aedf49a8d276d node-optimist-0.6.1/000077500000000000000000000000001227445567400143315ustar00rootroot00000000000000node-optimist-0.6.1/.travis.yml000066400000000000000000000000601227445567400164360ustar00rootroot00000000000000language: node_js node_js: - "0.8" - "0.10" node-optimist-0.6.1/LICENSE000066400000000000000000000021651227445567400153420ustar00rootroot00000000000000Copyright 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. node-optimist-0.6.1/example/000077500000000000000000000000001227445567400157645ustar00rootroot00000000000000node-optimist-0.6.1/example/bool.js000066400000000000000000000003531227445567400172560ustar00rootroot00000000000000#!/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 ? '.' : '') ); node-optimist-0.6.1/example/boolean_double.js000066400000000000000000000002311227445567400212670ustar00rootroot00000000000000#!/usr/bin/env node var argv = require('optimist') .boolean(['x','y','z']) .argv ; console.dir([ argv.x, argv.y, argv.z ]); console.dir(argv._); node-optimist-0.6.1/example/boolean_single.js000066400000000000000000000001731227445567400213030ustar00rootroot00000000000000#!/usr/bin/env node var argv = require('optimist') .boolean('v') .argv ; console.dir(argv.v); console.dir(argv._); node-optimist-0.6.1/example/default_hash.js000066400000000000000000000002001227445567400207410ustar00rootroot00000000000000#!/usr/bin/env node var argv = require('optimist') .default({ x : 10, y : 10 }) .argv ; console.log(argv.x + argv.y); node-optimist-0.6.1/example/default_singles.js000066400000000000000000000002111227445567400214640ustar00rootroot00000000000000#!/usr/bin/env node var argv = require('optimist') .default('x', 10) .default('y', 10) .argv ; console.log(argv.x + argv.y); node-optimist-0.6.1/example/divide.js000066400000000000000000000002371227445567400175700ustar00rootroot00000000000000#!/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); node-optimist-0.6.1/example/line_count.js000066400000000000000000000006311227445567400204610ustar00rootroot00000000000000#!/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-optimist-0.6.1/example/line_count_options.js000066400000000000000000000011731227445567400222360ustar00rootroot00000000000000#!/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)); }); node-optimist-0.6.1/example/line_count_wrap.js000066400000000000000000000013671227445567400215210ustar00rootroot00000000000000#!/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)); }); node-optimist-0.6.1/example/nonopt.js000066400000000000000000000001661227445567400176420ustar00rootroot00000000000000#!/usr/bin/env node var argv = require('optimist').argv; console.log('(%d,%d)', argv.x, argv.y); console.log(argv._); node-optimist-0.6.1/example/short.js000066400000000000000000000001411227445567400174550ustar00rootroot00000000000000#!/usr/bin/env node var argv = require('optimist').argv; console.log('(%d,%d)', argv.x, argv.y); node-optimist-0.6.1/example/string.js000066400000000000000000000003311227445567400176250ustar00rootroot00000000000000#!/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' ] */ node-optimist-0.6.1/example/usage-options.js000066400000000000000000000006701227445567400211220ustar00rootroot00000000000000var 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);node-optimist-0.6.1/example/xup.js000066400000000000000000000003011227445567400171300ustar00rootroot00000000000000#!/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'); } node-optimist-0.6.1/index.js000066400000000000000000000224411227445567400160010ustar00rootroot00000000000000var path = require('path'); var minimist = require('minimist'); 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 (processArgs, 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.env._ != undefined && process.argv[1] == process.env._) { self.$0 = process.env._.replace( path.dirname(process.execPath) + '/', '' ); } var options = { boolean: [], string: [], alias: {}, default: [] }; self.boolean = function (bools) { options.boolean.push.apply(options.boolean, [].concat(bools)); return self; }; self.string = function (strings) { options.string.push.apply(options.string, [].concat(strings)); return self; }; self.default = function (key, value) { if (typeof key === 'object') { Object.keys(key).forEach(function (k) { self.default(k, key[k]); }); } else { options.default[key] = value; } return self; }; self.alias = function (x, y) { if (typeof x === 'object') { Object.keys(x).forEach(function (key) { self.alias(key, x[key]); }); } else { options.alias[x] = (options.alias[x] || []).concat(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 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 parseArgs(args); }; 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(options.default)) .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(options.alias[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 (options.boolean[key]) type = '[boolean]'; if (options.string[key]) type = '[string]'; if (!wrap && dpadding.length > 0) { desc += dpadding; } var prelude = ' ' + kswitch + spadding; var extra = [ type, demanded[key] ? '[required]' : null , options.default[key] !== undefined ? '[default: ' + JSON.stringify(options.default[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 : function () { return parseArgs(processArgs) }, enumerable : true, }); function parseArgs (args) { var argv = minimist(args, options); argv.$0 = self.$0; 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; }; node-optimist-0.6.1/package.json000066400000000000000000000015711227445567400166230ustar00rootroot00000000000000{ "name" : "optimist", "version" : "0.6.1", "description" : "Light-weight option parsing with an argv hash. No optstrings attached.", "main" : "./index.js", "dependencies" : { "wordwrap" : "~0.0.2", "minimist" : "~0.0.1" }, "devDependencies" : { "hashish": "~0.0.4", "tap" : "~0.4.0" }, "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" } } node-optimist-0.6.1/readme.markdown000066400000000000000000000246001227445567400173340ustar00rootroot00000000000000# DEPRECATION NOTICE I don't want to maintain this module anymore since I just use [minimist](https://npmjs.org/package/minimist), the argument parsing engine, directly instead nowadays. See [yargs](https://github.com/chevex/yargs) for the modern, pirate-themed successor to optimist. [![yarrrrrrrgs!](http://i.imgur.com/4WFGVJ9.png)](https://github.com/chevex/yargs) 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 } } short numbers ------------- Short numeric `head -n5` style argument work too: $ node reflect.js -n123 -m456 { '3': true, '6': true, _: [], '$0': 'node ./reflect.js', n: 123, m: 456 } 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). node-optimist-0.6.1/test/000077500000000000000000000000001227445567400153105ustar00rootroot00000000000000node-optimist-0.6.1/test/_.js000066400000000000000000000033271227445567400160710ustar00rootroot00000000000000var 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(); }); }; } node-optimist-0.6.1/test/_/000077500000000000000000000000001227445567400155265ustar00rootroot00000000000000node-optimist-0.6.1/test/_/bin.js000077500000000000000000000001401227445567400166320ustar00rootroot00000000000000#!/usr/bin/env node var argv = require('../../index').argv console.log(JSON.stringify(argv._)); node-optimist-0.6.1/test/dash.js000066400000000000000000000012221227445567400165620ustar00rootroot00000000000000var optimist = require('../index'); var test = require('tap').test; test('-', function (t) { t.plan(5); t.deepEqual( fix(optimist.parse([ '-n', '-' ])), { n: '-', _: [] } ); t.deepEqual( fix(optimist.parse([ '-' ])), { _: [ '-' ] } ); t.deepEqual( fix(optimist.parse([ '-f-' ])), { f: '-', _: [] } ); t.deepEqual( fix(optimist([ '-b', '-' ]).boolean('b').argv), { b: true, _: [ '-' ] } ); t.deepEqual( fix(optimist([ '-s', '-' ]).string('s').argv), { s: '-', _: [] } ); }); function fix (obj) { delete obj.$0; return obj; } node-optimist-0.6.1/test/parse.js000066400000000000000000000243761227445567400167740ustar00rootroot00000000000000var 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('newlines in params' , function (t) { var args = optimist.parse([ '-s', "X\nX" ]) t.same(args, { _ : [], s : "X\nX", $0 : $0 }); // reproduce in bash: // VALUE="new // line" // node program.js --s="$VALUE" args = optimist.parse([ "--s=X\nX" ]) t.same(args, { _ : [], s : "X\nX", $0 : $0 }); 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(); }); node-optimist-0.6.1/test/parse_modified.js000066400000000000000000000004751227445567400206260ustar00rootroot00000000000000var optimist = require('../'); var test = require('tap').test; test('parse with modifier functions' , function (t) { t.plan(1); var argv = optimist().boolean('b').parse([ '-b', '123' ]); t.deepEqual(fix(argv), { b: true, _: ['123'] }); }); function fix (obj) { delete obj.$0; return obj; } node-optimist-0.6.1/test/short.js000066400000000000000000000005741227445567400170130ustar00rootroot00000000000000var optimist = require('../index'); var test = require('tap').test; test('-n123', function (t) { t.plan(1); var parse = optimist.parse([ '-n123' ]); t.equal(parse.n, 123); }); test('-123', function (t) { t.plan(3); var parse = optimist.parse([ '-123', '456' ]); t.equal(parse['1'], true); t.equal(parse['2'], true); t.equal(parse['3'], 456); }); node-optimist-0.6.1/test/usage.js000066400000000000000000000152051227445567400167550ustar00rootroot00000000000000var 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, }; }; node-optimist-0.6.1/test/whitespace.js000066400000000000000000000003171227445567400200030ustar00rootroot00000000000000var optimist = require('../'); var test = require('tap').test; test('whitespace should be whitespace' , function (t) { t.plan(1); var x = optimist.parse([ '-x', '\t' ]).x; t.equal(x, '\t'); });