Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Initial commit.

  • Loading branch information...
commit 90b646213917df3ef1ecf363f933f9be25f4cf32 0 parents
Paul Miller authored
3  .gitignore
@@ -0,0 +1,3 @@
+.DS_Store
+node_modules/
+lib/
10 Cakefile
@@ -0,0 +1,10 @@
+{spawn} = require 'child_process'
+
+
+task 'build', 'build argumentum from source', (callback) ->
+ spawn 'coffee', ['-c', '-o', 'lib', 'src']
+
+task 'test', 'run test suite', (callback) ->
+ proc = spawn 'nodeunit', ['test']
+ proc.stdout.on 'data', (buffer) ->
+ process.stdout.write buffer.toString()
96 README.md
@@ -0,0 +1,96 @@
+# Argumentum
+Argumentum is a no-bullshit option parser for node. It doesn't have
+complicated chainable APIs so it's much more easier to use.
+
+## Example
+Example usage (in CoffeeScript):
+
+```coffeescript
+argumentum = require 'argumentum'
+
+config =
+ script: 'app'
+ commandRequired: yes
+ commands:
+ new:
+ help: 'Create new project'
+ options:
+ appPath:
+ position: 1
+ help: 'application path'
+ metavar: 'APP_PATH'
+ required: yes
+
+ buildPath:
+ abbr: 'o'
+ help: 'build path'
+ metavar: 'DIRECTORY'
+ full: 'output'
+
+ callback: (options) ->
+ 'callback called'
+
+ options:
+ version:
+ abbr: 'v'
+ help: 'display app version'
+ flag: true
+ callback: ->
+ 'version called'
+
+argumentum.load(config).parse()
+```
+
+Example project that uses argumentum: [brunch](https://github.com/brunch/brunch/blob/master/src/command.coffee)
+
+## Documentation
+There are two public API functions in argumentum:
+
+* `argumentum.load()` takes config object (ordinary JS object).
+* `argumentum.parse()` parses some string and does appropriate actions. If
+no argument was provided, it parses STDIN.
+
+### Config object
+
+* `commandRequired`: print usage if no command was provided? Usually disabled
+in software that works with STDIN.
+* `script`: name of script that will show in usage.
+* `options`: a js object, where keys are option names and values are their
+info. These are options that will be global to each command (`app --globalOpt`).
+Option info keys:
+ * `abbr`: short option name. E.g. `-v` as an alias to `--version`
+ * `flag`: if option was specified then it's true else false.
+ * `full`: if specified, this name will be used in parser and documentation
+ and option name will be used as a part of `options` passed to `callback`.
+ * `help`: description.
+ * `metavar`: used in help. Example: `DIRECTORY`, `FILE` etc.
+ * `position`: makes option positional. E.g. `app command a b c` will call
+ options with positions 1, 2 and 3.
+ * `callback`: function that will be executed on calling. If it returns
+ string, string will be printed to STDOUT.
+* `commands`: a js object, where keys are command names and values are their
+info. Command info keys:
+ * `abbr`: short command name. E.g. you can make `g` as an alias to
+ `generate`.
+ * `help`: description.
+ * `options`: options that are local to each command
+ (`app command --localOpt`). Have same semantics
+ as global options.
+ * `callback`: function that will be executed on command calling. It takes
+ a list of options as first argument. If it returns
+ string, string will be printed to STDOUT.
+
+## License
+This project is based on [nomnom](https://github.com/harthur/nomnom)
+by Heather Arthur.
+
+(The MIT License)
+
+Copyright (c) 2011 Paul Miller (paulmillr.com)
+
+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.
+
12 package.json
@@ -0,0 +1,12 @@
+{
+ "name": "argumentum",
+ "description": "Option parser with generated usage and commands",
+ "version": "0.6.0",
+ "author": "Paul Miller (http://paulmillr.com)",
+ "repository": {
+ "type": "git",
+ "url": "http://github.com/paulmillr/argumentum.git"
+ },
+ "main": "./lib/argumentum",
+ "keywords": ["arguments", "option parser", "command line", "options", "parser", "nomnom"]
+}
357 src/argumentum.coffee
@@ -0,0 +1,357 @@
+path = require 'path'
+
+
+# Shell color manipulation tools.
+colors =
+ black: 30
+ red: 31
+ green: 32
+ brown: 33
+ blue: 34
+ purple: 35
+ cyan: 36
+ gray: 37
+ none: ''
+ reset: 0
+
+
+getColor = (color) ->
+ colors[color.toString()] or colors.none
+
+
+colorize = (text, color) ->
+ "\x16[#{getColor(color)}m#{text}\x16[#{getColor('reset')}m"
+
+
+spaces = (count) ->
+ Array(+count + 1).join ' '
+
+
+setter = (prop) -> (val) ->
+ @[prop] = val
+ this
+
+
+booleanSetter = (prop) -> (val) ->
+ @[prop] = !!val
+ this
+
+
+# Extends the object with properties from another object.
+# Example
+#
+# extend {a: 5, b: 10}, {b: 15, c: 20, e: 50}
+# # => {a: 5, b: 15, c: 20, e: 50}
+#
+extend = (obj, objects...) ->
+ for object in objects
+ obj[key] = val for own key, val of object
+ obj
+
+
+isEmptyObject = (object) ->
+ return false for own key of object
+ true
+
+
+parseArgument = (str) ->
+ charMatch = /^\-(\w+?)$/.exec str
+ chars = charMatch and charMatch[1].split('')
+ fullMatch = /^\-\-(no\-)?(.+?)(?:=(.+))?$/.exec str
+ full = fullMatch and fullMatch[2]
+ isValue = str? and (str is '' or /^[^\-].*/.test str)
+ if isValue
+ value = str
+ else if full
+ value = if fullMatch[1] then false else fullMatch[3]
+ {str, chars, full, value, isValue}
+
+
+parseOption = (opt = {}) ->
+ strings = (opt.string or '').split(',')
+ for string in strings
+ string = string.trim()
+ if matches = string.match /^\-([^-])(?:\s+(.*))?$/
+ abbr = matches[1]
+ metavar = matches[2]
+ else if matches = string.match /^\-\-(.+?)(?:[=\s]+(.+))?$/
+ full = matches[1]
+ metavar or= matches[2]
+ matches or= []
+ abbr = opt.abbr or abbr
+ full = opt.full or full
+ metavar = opt.metavar or metavar
+ if opt.string
+ string = opt.string
+ else if not opt.position?
+ string = ''
+ if abbr
+ string += "-#{abbr}"
+ string += " #{metavar}" if metavar
+ string += ', '
+ string += "--#{(full or opt.name)}"
+ string += " #{metavar}" if metavar
+ name = opt.name or full or abbr
+ extend opt, {
+ name, string, abbr, full, metavar,
+ matches: (arg) ->
+ arg in [opt.full, opt.abbr, opt.position, opt.name] or
+ (opt.list and arg >= opt.position)
+ }
+
+
+class ArgumentParser
+ constructor: ->
+ return (new ArgumentParser arguments...) unless this instanceof ArgumentParser
+ @commands = {}
+ @commandAbbrs = {}
+ @specs = {}
+
+ command: (name) ->
+ if name
+ command = @commands[name] =
+ name: name
+ specs: {}
+ else
+ command = @fallback = specs: {}
+
+ chain =
+ options: (specs) ->
+ command.specs = specs
+ chain
+
+ option: (name, spec) ->
+ command.specs[name] = spec
+ chain
+
+ callback: (cb) ->
+ command.cb = cb
+ chain
+
+ help: (help) ->
+ command.help = help
+ chain
+
+ usage: (usage) ->
+ command._usage = usage
+ chain
+
+ abbr: (abbr) =>
+ command.abbr = abbr
+ @commandAbbrs[abbr] = command
+ chain
+
+ # Old API.
+ opts: (specs) ->
+ @options specs
+ chain
+
+ nocommand: ->
+ @command()
+
+ options: setter "specs"
+ usage: setter "_usage"
+ printer: setter "print"
+ script: setter "_script"
+ help: setter "_help"
+ withColors: booleanSetter "_withColors"
+ commandRequired: booleanSetter "_commandRequired"
+
+ option: (name, spec) ->
+ @specs[name] = spec
+ this
+
+ _colorize: (text, color) ->
+ if @_withColors then colorize(text, color) else text
+
+ getUsage: ->
+ return @command._usage if @command and @command._usage
+ return @fallback._usage if @fallback and @fallback._usage
+ return @_usage if @_usage
+
+ indent = (str) -> spaces(2) + str
+ str = "Usage: #{@_script}"
+
+ positionals = @specs
+ .filter((opt) -> opt.position?)
+ .sort((left, right) -> left.position > right.position)
+ options = @specs.filter (opt) -> not opt.position?
+
+ if positionals.length
+ for pos in positionals
+ str += ' '
+ posStr = pos.string or "<#{pos.name or "arg#{pos.position}"}>#{['...' if pos.list]}"
+ str += posStr
+ else if @_printAllCommands
+ str += ' [command] [options]'
+ str += '\n\nPossible commands are:\n'
+ for name, command of @commands
+ str += indent "#{@_script} #{command.name}"
+ str += ": #{command.help}" if command.help
+ str += " (short-cut alias: '#{command.abbr}')" if command.abbr
+ str += '\n'
+ str += "\nTo get help on individual command, execute '#{@_script} <command> --help'"
+
+ str += @_colorize ' [options]', 'blue' if options.length
+ str += '\n\n' if options.length or positionals.length
+
+ # Get indentation of longest positional.
+ longest = positionals.reduce ((max, pos) -> Math.max max, pos.name.length), 0
+ for pos in positionals
+ posStr = pos.string or pos.name
+ str += posStr + spaces longest - posStr.length + 5
+ str += @_colorize (pos.help or ''), 'gray'
+ str += '\n'
+ str += '\n' if positionals.length and options.length
+ if options.length
+ visible = (opt) -> not opt.hidden
+ str += @_colorize 'Options:\n', 'blue'
+ longest = options
+ .filter(visible)
+ .reduce ((max, opt) -> Math.max max, opt.string.length), 0
+ str += options
+ .filter(visible)
+ .map (opt) =>
+ indentation = spaces longest - opt.string.length
+ help = @_colorize (opt.help or ''), 'gray'
+ indent "#{opt.string} #{indentation} #{help}"
+ .join('\n')
+ str += "\n\nDescription:\n#{indent(@_help)}" if @_help
+ str
+
+ parse: (argv) ->
+ @print ?= (str) ->
+ console.log str
+ process.exit 0
+
+ @_help ?= ''
+ @_script ?= "#{process.argv[0]} #{path.basename(process.argv[1])}"
+ @specs ?= {}
+
+ process.argv[2] = '--help' if @_commandRequired and not process.argv[2]
+
+ argv ?= process.argv[2..]
+ arg = parseArgument(argv[0]).isValue and argv[0]
+ command = arg and @commands[arg] or @commandAbbrs[arg]
+ commandExpected = not isEmptyObject @commands
+ if commandExpected
+ if command
+ extend @specs, command.specs
+ @_script += " #{command.name}"
+ @_help = command.help if command.help
+ @command = command
+ else if arg
+ return @print "#{@_script}: no such command '#{arg}'"
+ else
+ @_printAllCommands = yes
+ if @fallback
+ extend @specs, @fallback.specs
+ @_help = @fallback.help
+ unless @specs.length
+ @specs = for key, value of @specs
+ value.name = key
+ value
+ @specs = @specs.map parseOption
+
+ return @print @getUsage() if '--help' in argv or '-h' in argv
+
+ options = {}
+ args = argv.map(parseArgument).concat parseArgument()
+ positionals = []
+
+ args.reduce (arg, val) =>
+ if arg.isValue
+ positionals.push arg.value
+ else if arg.chars
+ last = arg.chars.pop()
+ for ch in arg.chars
+ @setOption options, ch, true
+ if @opt(last).flag
+ @setOption options, last, true
+ else if val.isValue
+ @setOption options, last, val.value
+ return parseArgument()
+ else
+ @print "'-#{(@opt(last).name or last)}' expects a value\n\n#{@getUsage()}"
+ else if arg.full
+ value = arg.value
+ unless value?
+ if @opt(arg.full).flag
+ value = true
+ else if val.isValue
+ @setOption options, arg.full, val.value
+ return parseArgument()
+ else
+ @print "'--#{(@opt(arg.full).name or arg.full)}' expects a value\n\n#{@getUsage()}"
+ @setOption options, arg.full, value
+ val
+
+ for pos, index in positionals
+ @setOption options, index, pos
+
+ for opt in @specs when not options[opt.name]?
+ if opt.default?
+ options[opt.name] = opt.default
+ else if opt.required
+ @print "#{opt.name} argument is required\n\n#{@getUsage()}"
+ if command?.cb?
+ message = command.cb options
+ @print message if typeof message is 'string'
+ else if @fallback?.cb?
+ @fallback.cb options
+ options
+
+ opt: (arg) ->
+ match = parseOption()
+ for opt in @specs when opt.matches arg
+ match = opt
+ match
+
+ setOption: (options, arg, value) ->
+ option = @opt arg
+ if option.callback
+ message = option.callback value
+ @print message if typeof message is 'string'
+ if option.type isnt 'string'
+ try
+ value = JSON.parse value
+ name = option.name or arg
+ if option.choices and value not in option.choices
+ @print "#{name} must be one of: #{option.choices.join(', ')}"
+ if option.list
+ options[name] ?= []
+ options[name].push value
+ else
+ options[name] = value
+
+ # Old API.
+ parseArgs: -> @parse arguments...
+ scriptName: -> @script arguments...
+ globalOpts: -> @options arguments...
+ opts: -> @options arguments...
+ colors: -> @withColors arguments...
+ nom: (argv) -> @parse argv
+ # Old API end.
+
+ load: (config) ->
+ for own name, data of config
+ if name is 'commands'
+ for own commandName, commandData of data
+ command = @command commandName
+ for own attrName, attrValue of commandData
+ command[attrName] attrValue
+ else
+ try
+ data = data this if typeof data is 'function'
+ @[name] data
+ catch error
+ this
+
+
+argumentParser = new ArgumentParser
+for i, method of argumentParser when typeof method is 'function'
+ ArgumentParser[i] = method.bind argumentParser
+
+exports.ArgumentParser = ArgumentParser
+exports.load = (config) ->
+ (new ArgumentParser).load config
33 test/callback.js
@@ -0,0 +1,33 @@
+var argumentum = require('../lib/argumentum').ArgumentParser;
+
+exports.testVersion = function(test) {
+ test.expect(1);
+
+ argumentum().options({
+ date: {
+ callback: function(date) {
+ test.equal(date, '2010-02-03', 'date should match value')
+ }
+ }
+ }).parse(['--date=2010-02-03']);
+
+ test.done();
+}
+
+exports.testReturnString = function(test) {
+ test.expect(1);
+
+ argumentum().options({
+ version: {
+ flag: true,
+ callback: function() {
+ return 'v0.3';
+ }
+ }
+ })
+ .printer(function(string) {
+ test.equal(0, string.indexOf('v0.3'))
+ test.done();
+ })
+ .parse(['--version']);
+}
116 test/commands.js
@@ -0,0 +1,116 @@
+var argumentum = require('../lib/argumentum').ArgumentParser;
+
+function strip(str) {
+ return str.replace(/\s+/g, '');
+}
+
+exports.testCallback = function(test) {
+ test.expect(1);
+
+ var parser = argumentum();
+ parser.command('run').callback(function(options) {
+ test.equal(options.v, 3);
+ });
+ parser.command('other').callback(function() {
+ test.ok(false, 'callback for other command shouldn\'t be called');
+ });
+
+ parser.parse(['run','-v', '3']);
+ test.done();
+}
+
+exports.testMissingCommand = function(test) {
+ test.expect(1);
+
+ var parser = argumentum().scriptName('test');
+
+ parser.command('run');
+
+ parser.printer(function(string) {
+ test.equal(string, 'test: no such command \'other\'');
+ test.done();
+ });
+
+ parser.parse(['other']);
+}
+
+exports.testNoCommand = function(test) {
+ test.expect(2);
+
+ var parser = argumentum();
+
+ parser.nocommand()
+ .options({version: {flag: true}})
+ .callback(function(options) {
+ test.strictEqual(options.version, true);
+ })
+ .usage('fallback usage');
+
+ parser.command('run');
+
+ var options = parser.parse(['--version']);
+
+ test.strictEqual(options.version, true);
+ test.done();
+}
+
+function createParser() {
+ var parser = argumentum().scriptName('test')
+ .options({
+ debug: {
+ flag: true
+ }
+ });
+
+ parser.command('run')
+ .options({
+ file: {
+ help: 'file to run'
+ }
+ })
+ .help('run all');
+
+ parser.command('test').usage('test usage');
+
+ parser.nocommand()
+ .options({
+ verbose: {
+ flag: true
+ }
+ })
+ .help('nocommand');
+
+ return parser;
+}
+
+exports.testUsage = function(test) {
+ test.expect(4);
+
+ var parser = createParser();
+ parser.printer(function(string) {
+ test.equal(strip(string), 'testusage');
+ });
+ parser.parse(['test', '-h']);
+
+ parser = createParser();
+ parser.printer(function(string) {
+ test.equal(strip(string), 'Usage:testrun[options]Options:--debug--filefiletorunDescription:runall');
+ });
+ parser.parse(['run', '-h']);
+
+ parser = createParser();
+ parser.printer(function(string) {
+ test.equal(strip(string), 'Usage:test[command][options]Possiblecommandsare:testrun:runalltesttestTogethelponindividualcommand,execute\'test<command>--help\'[options]Options:--debug--verboseDescription:nocommand');
+ });
+ parser.parse(['-h']);
+
+ parser = createParser();
+ parser.nocommand()
+ .usage('fallback');
+ parser.printer(function(string) {
+ test.equal(strip(string), 'fallback');
+ });
+ parser.parse(['-h']);
+
+ test.done();
+}
82 test/config.js
@@ -0,0 +1,82 @@
+var argumentum = require('../lib/argumentum');
+
+
+var config = {
+ commands: {
+ 'new': {
+ abbr: 'n',
+ help: 'Create new project',
+ options: {
+ appPath: {
+ position: 1,
+ help: 'application path',
+ metavar: 'APP_PATH',
+ required: true
+ },
+ buildPath: {
+ abbr: 'o',
+ help: 'build path',
+ metavar: 'DIRECTORY',
+ full: 'output'
+ }
+ },
+ callback: function(options) {
+ return 'callback called';
+ }
+ },
+ generate: {
+ help: 'Generate model, view or route for current project',
+ options: {
+ generator: {
+ position: 1,
+ help: 'generator type',
+ metavar: 'GENERATOR',
+ choices: ['collection', 'model', 'router', 'style', 'template', 'view'],
+ required: true
+ },
+ name: {
+ position: 2,
+ help: 'generator class name / filename',
+ metavar: 'NAME',
+ required: true
+ }
+ },
+ callback: function(options) {
+ return 'generate called';
+ }
+ }
+ },
+ options: {
+ version: {
+ abbr: 'v',
+ help: 'display app version',
+ flag: true,
+ callback: function() {
+ return 'version called';
+ }
+ }
+ },
+ script: 'app'
+};
+
+var generateParser = function(test, expected) {
+ return argumentum.load(config).printer(function(string) {
+ test.equal(string, expected);
+ });
+};
+
+
+exports.testConfig = function(test) {
+ test.expect(3);
+
+ parser = generateParser(test, config.options.version.callback());
+ parser.parse(['--version']);
+
+ parser = generateParser(test, config.commands['new'].callback());
+ parser.parse(['new', '--appPath', '.']);
+
+ parser = generateParser(test, config.commands['new'].callback());
+ parser.parse(['n', '--appPath', '.']);
+
+ test.done();
+};
59 test/expected.js
@@ -0,0 +1,59 @@
+var argumentum = require('../lib/argumentum').ArgumentParser;
+
+var opts = {
+ file: {
+ position: 0,
+ required: true
+ }
+}
+
+var parser = argumentum().options(opts);
+
+exports.testFlag = function(test) {
+ test.expect(1);
+
+ argumentum().options({
+ file: {
+ position: 0,
+ }
+ })
+ .printer(function(string) {
+ test.equal(0, string.indexOf('\'--key1\' expects a value'))
+ test.done();
+ })
+ .parse(['--key1']);
+}
+
+exports.testRequired = function(test) {
+ test.expect(1);
+
+ argumentum().options({
+ file: {
+ required: true
+ }
+ })
+ .printer(function(string) {
+ test.equal(0, string.indexOf('file argument is required'))
+ test.done();
+ })
+ .parse([]);
+}
+
+exports.testChoices = function(test) {
+ test.expect(2);
+
+ var parser = argumentum().options({
+ color: {
+ choices: ['green', 'blue']
+ }
+ })
+ .printer(function(string) {
+ test.equal(0, string.indexOf('color must be one of: green, blue'))
+ });
+
+ parser.parse(['--color', 'red']);
+
+ var options = parser.parse(['--color', 'green']);
+ test.equal(options.color, 'green');
+ test.done();
+}
69 test/matching.js
@@ -0,0 +1,69 @@
+var argumentum = require('../lib/argumentum').ArgumentParser;
+
+var opts = {
+ pos1: {
+ position: 0
+ },
+ pos2: {
+ position: 1
+ },
+ flag1: {
+ flag: true
+ },
+ debug: {
+ abbr: 'd'
+ },
+ numLines: {
+ abbr: 'n',
+ full: 'num-lines'
+ },
+ version: {
+ string: '-v, --version'
+ },
+ config: {
+ string: '-c FILE, --config=FILE'
+ },
+ skey : {
+ string: '-k val'
+ },
+ skey2: {
+ string: '-k2 val2, --key2 val2'
+ },
+ skey3: {
+ string: '--key3=val'
+ },
+ skey4: {
+ string: '--key4=val, -y val'
+ }
+}
+
+var parser = argumentum().options(opts);
+
+exports.testPositional = function(test) {
+ var options = parser.parse(['--flag1', 'val1', '--config', 'file', 'val2']);
+
+ test.equal(options.pos1, 'val1');
+ test.equal(options.pos2, 'val2');
+ test.done();
+}
+
+exports.testAbbr = function(test) {
+ var options = parser.parse(['-d', 'yes', '--num-lines', '3']);
+
+ test.equal(options.debug, 'yes')
+ test.equal(options.numLines, 3)
+ test.done();
+}
+
+exports.testString = function(test) {
+ var options = parser.parse(['-k', 'val', '--config=test.js',
+ '--key2', 'val2', '--key3', 'val3', '--key4=val4', '-v', 'v0.3']);
+
+ test.equal(options.version, 'v0.3')
+ test.equal(options.config, 'test.js')
+ test.equal(options.skey, 'val')
+ test.equal(options.skey2, 'val2')
+ test.equal(options.skey3, 'val3')
+ test.equal(options.skey4, 'val4')
+ test.done();
+}
44 test/option.js
@@ -0,0 +1,44 @@
+var argumentum = require('../lib/argumentum').ArgumentParser;
+
+var parser = argumentum()
+ .option('debug', {
+ abbr: 'x',
+ flag: true,
+ help: 'Print debugging info'
+ })
+ .option('config', {
+ abbr: 'c',
+ default: 'config.json',
+ help: 'JSON file with tests to run'
+ })
+ .option('version', {
+ flag: true,
+ help: 'print version and exit',
+ callback: function() {
+ return 'version 1.2.4';
+ }
+ });
+
+
+exports.testOption = function(test) {
+ var opts = parser.parse(['-x', '--no-verbose']);
+
+ test.strictEqual(opts.debug, true);
+ test.equal(opts.config, 'config.json');
+ test.done();
+}
+
+
+exports.testCommandOption = function(test) {
+ var parser = argumentum()
+ parser.command('test')
+ .option('fruit', {
+ abbr: 'f',
+ flag: true
+ })
+
+ var opts = parser.parse(['test', '-f']);
+
+ test.strictEqual(opts.fruit, true);
+ test.done();
+}
93 test/usage.js
@@ -0,0 +1,93 @@
+var argumentum = require('../lib/argumentum').ArgumentParser;
+
+function strip(str) {
+ return str.replace(/\s+/g, '');
+};
+
+var opts = {
+ apple: {
+ abbr: 'a',
+ help: 'how many apples'
+ },
+
+ banana: {
+ full: 'b-nana'
+ },
+
+ carrot: {
+ string: '-c NUM, --carrots=NUM'
+ },
+
+ dill: {
+ metavar: 'PICKLE'
+ },
+
+ egg: {
+ position: 0,
+ help: 'robin'
+ }
+}
+
+var parser = argumentum().options(opts).help('all the best foods').scriptName('test');
+
+var expected = 'Usage:test<egg>[options]eggrobinOptions:-a,--applehowmanyapples--b-nana-cNUM,--carrots=NUM--dillPICKLEDescription:allthebestfoods'
+
+exports.testH = function(test) {
+ test.expect(1);
+
+ parser.printer(function(string) {
+ test.equal(strip(string), expected)
+ test.done();
+ })
+ .parse(['-h']);
+}
+
+exports.testHelp = function(test) {
+ test.expect(1);
+
+ parser.printer(function(string) {
+ test.equal(strip(string), expected)
+ test.done();
+ })
+ .parse(['--help']);
+}
+
+exports.testScriptName = function(test) {
+ test.expect(1);
+
+ argumentum()
+ .script('test')
+ .printer(function(string) {
+ test.equal(strip(string),'Usage:test')
+ test.done();
+ })
+ .parse(['-h']);
+}
+
+exports.testUsage = function(test) {
+ test.expect(1);
+
+ parser
+ .usage('test usage')
+ .printer(function(string) {
+ test.equal(string, 'test usage')
+ test.done();
+ })
+ .parse(['--help']);
+}
+
+exports.testHidden = function(test) {
+ test.expect(1);
+
+ argumentum().options({
+ file: {
+ hidden: true
+ }
+ })
+ .scriptName('test')
+ .printer(function(string) {
+ test.equal(strip('Usage:test[options]Options:'), strip(string))
+ test.done();
+ })
+ .parse(['-h']);
+}
74 test/values.js
@@ -0,0 +1,74 @@
+var argumentum = require('../lib/argumentum').ArgumentParser;
+
+var opts = {
+ debug: {
+ flag: true
+ },
+ verbose: {
+ flag: true,
+ default: true
+ },
+ list1: {
+ list: true
+ },
+ list2: {
+ list: true
+ },
+ list3: {
+ position: 1,
+ list: true
+ },
+ num1: {
+ type: 'string'
+ },
+ def1: {
+ default: 'val1'
+ },
+ def2: {
+ default: 'val1'
+ }
+}
+
+var parser = argumentum().options(opts);
+
+exports.testFlag = function(test) {
+ var options = parser.parse(['--debug', 'pos0', '--no-verbose']);
+
+ test.strictEqual(options.debug, true);
+ test.strictEqual(options.verbose, false);
+ test.equal(options[0], 'pos0');
+ test.done();
+}
+
+exports.testList = function(test) {
+ var options = parser.parse(['pos0', 'pos1', '--list1=val0', '--list2', 'val1',
+ '--list2', 'val2', 'pos2']);
+
+ test.deepEqual(options.list1, ['val0']);
+ test.deepEqual(options.list2, ['val1', 'val2']);
+ test.deepEqual(options.list3, ['pos1', 'pos2']);
+ test.done();
+}
+
+exports.testDefault = function(test) {
+ var options = parser.parse(['--def2', 'val2', '--def3', 'val3']);
+
+ test.strictEqual(options.def1, 'val1');
+ test.strictEqual(options.def2, 'val2');
+ test.strictEqual(options.def3, 'val3');
+ test.done();
+}
+
+exports.testTypes = function(test) {
+ var options = parser.parseArgs(['', '-x', '3.14', '-w', 'true', '-q', '120',
+ '--num1', '4']);
+
+ test.strictEqual(options[0], '');
+ test.strictEqual(options.x, 3.14);
+ test.strictEqual(options.w, true);
+ test.strictEqual(options.q, 120);
+ test.strictEqual(options.num1, '4');
+ test.done();
+}
+
+
Please sign in to comment.
Something went wrong with that request. Please try again.