Permalink
Browse files

an opt can specify a callback

  • Loading branch information...
1 parent 98697eb commit 8293e17e00445bcd6550328a9cf3f21bbec8c47f @harthur committed Apr 18, 2011
Showing with 97 additions and 40 deletions.
  1. +41 −22 README.md
  2. +24 −18 lib/nomnom.js
  3. +32 −0 test/callback.js
View
@@ -3,14 +3,14 @@ nomnom is an option parser for node and CommonJS. It noms your args and gives th
var options = require("nomnom")
.opts({
+ debug: {
+ string: '-d, --debug',
+ help: 'Print debugging info'
+ },
config: {
string: '-c PATH, --config=PATH',
default: 'config.json',
help: 'JSON file with tests to run'
- },
- debug: {
- string: '-d, --debug',
- help: 'Print debugging info'
}
})
.parseArgs();
@@ -34,13 +34,12 @@ for [node.js](http://nodejs.org/) and [npm](http://github.com/isaacs/npm):
# Commands
Nomnom supports command-based interfaces, e.g. with git: `git add -p` and `git rebase -i` where `add` and `rebase` are the commands:
- var parser = require("nomnom")
- .opts({ // global opts
- debug: {
- string: '-d, --debug',
- help: 'print debugging info'
- }
- });
+ var parser = nomnom.opts({
+ debug: {
+ string: '-d, --debug',
+ help: 'print debugging info'
+ }
+ });
parser.command('sanity')
.opts({
@@ -72,24 +71,44 @@ By default, nomnom parses [node](http://nodejs.org/)'s `process.argv`. You can a
Values are JSON parsed, so `--debug=true --count=3 --file=log.txt` would give you:
- { debug: true,
- count: 3,
- file: "log.txt"
+ {
+ "debug": true,
+ "count": 3,
+ "file": "log.txt"
}
### positional args
All parsed arguments that don't fit the `-a` or `--atomic` format and aren't attached to an option are positional and can be matched on via the `position`:
- var options = require("nomnom")
- .opts({
- filename: {
- position: 0,
- help: 'file to edit'
- }
- })
- .parseArgs();
+ var options = nomnom.opts({
+ filename: {
+ position: 0,
+ help: 'file to edit'
+ }
+ }).parseArgs();
console.log(options.filename);
+
+### callbacks
+You can provide a callback that will be executed as soon as the arg is encountered. If the callback returns a string it will print the string and exit:
@jsocol
jsocol Apr 18, 2011 Contributor

With this change this is a complete superset and improvement of the functionality in the node optparse port.

+
+ var opts = {
+ version: {
+ string: '--version'
+ callback: function() {
+ return "version 1.2.4";
+ }
+ },
+ date: {
+ string: '-d YYYY-MM-DD, --date=YYYY-MM-DD',
+ callback: function(date) {
+ if(!(/^\d{4}\-\d\d\-\d\d$/).test(date))
+ return "date must be in format yyyy-mm-dd";
+ }
+ }
+ }
+
+ var options = nomnom.opts(opts).parseArgs();
### printing usage
Nomnom prints out a usage message if `--help` or `-h` is an argument. You can override the usage string with `usage`:
View
@@ -20,9 +20,16 @@ function ArgParser() {
});
return match;
};
-
- function optName(arg) {
- return opt(arg).name || arg;
+
+ function setOption(options, arg, value) {
+ var option = opt(arg);
+ if(option.callback) {
+ var message = option.callback(value);
+ if(typeof message == "string"){
+ parser.print(message);
+ }
+ }
+ options[option.name || arg] = value;
};
var parser = {
@@ -91,7 +98,7 @@ function ArgParser() {
printHelp = true;
argv = parserOpts.argv;
}
- var print = parser.print || function(str) {
+ parser.print = parser.print || function(str) {
require("sys").puts(str);
process.exit(0);
};
@@ -118,7 +125,7 @@ function ArgParser() {
// command specified e.g. 'git add -p'
var command = parser.commands[commandName];
if(!command)
- print(parser.script + ": no such command '" + commandName + "'");
+ parser.print(parser.script + ": no such command '" + commandName + "'");
parser.specs = _(command.specs).extend(parser.specs);
parser.script += " " + command.name;
if(command.help)
@@ -140,18 +147,17 @@ function ArgParser() {
/* parse the args */
if(printHelp && (argv.indexOf("--help") != -1
|| argv.indexOf("-h") != -1))
- print(parser.getUsage());
-
+ parser.print(parser.getUsage());
+
var options = {};
parser.specs.forEach(function(opt) {
options[opt.name] = opt.default;
- }, parser);
-
+ });
+
args = argv.concat([""]).map(function(arg) {
return Arg(arg);
});
var positionals = [];
- var that = parser;
args.reduce(function(arg, val) {
/* word */
@@ -162,13 +168,13 @@ function ArgParser() {
else if(arg.chars) {
/* -cfv */
(arg.chars).forEach(function(ch) {
- options[optName(ch)] = true;
- }, that);
+ setOption(options, ch, true);
+ });
/* -c 3 */
if(val.isValue) {
var expectsValue = opt(arg.lastChar).expectsValue();
if(expectsValue) {
- options[optName(arg.lastChar)] = val.value;
+ setOption(options, arg.lastChar, val.value);
return Arg(""); // skip next turn - swallow arg
}
}
@@ -179,20 +185,20 @@ function ArgParser() {
/* --debug */
if(value == undefined)
value = true;
- options[optName(arg.lg)] = value;
+ setOption(options, arg.lg, value);
}
return val;
});
positionals.forEach(function(pos, index) {
- options[optName(index)] = pos;
- }, parser);
+ setOption(options, index, pos);
+ });
// exit if required arg isn't present
parser.specs.forEach(function(opt) {
if(opt.required && !options[opt.name])
- print(opt.name + " argument is required");
- }, parser);
+ parser.print(opt.name + " argument is required");
+ });
if(command && command.callback)
command.callback(options);
View
@@ -0,0 +1,32 @@
+var nomnom = require("../lib/nomnom"),
+ assert = require('assert');
+
+var opts = {
+ version: {
+ string: '--version',
+ callback: function() {
+ assert.ok(true, "called version callback");
+ }
+ },
+ date: {
+ string: '-d YYYY-MM-DD, --date=YYYY-MM-DD',
+ callback: function(date) {
+ assert.equal(date, "2010-02-03", "date should match value")
+ }
+ }
+}
+
+var options = nomnom().opts(opts).parseArgs(["--version", "--date=2010-02-03"]);
+
+/* // exits process
+nomnom().opts({
+ version: {
+ string: '--version',
+ callback: function() {
+ return "called version callback";
+ }
+ }
+}).parseArgs(["--version"]);
+
+assert.ok(false, "should have exited when --version specified");
+*/

0 comments on commit 8293e17

Please sign in to comment.