diff --git a/lib/nl/options.js b/lib/nl/options.js index 800b701..2ee3466 100644 --- a/lib/nl/options.js +++ b/lib/nl/options.js @@ -24,10 +24,10 @@ OTHER DEALINGS IN THE SOFTWARE. */ -var sys = require('sys'); +var util = require('util'); var url = require('url'); var path = require('path'); -var optparse = require('./optparse'); +var optparse = require('optparse'); // Default options var testConfig = { @@ -60,7 +60,7 @@ var switches = [ var parser; var help = exports.help = function() { - sys.puts(parser); + util.log(parser); process.exit(); }; diff --git a/lib/nl/optparse-README.md b/lib/nl/optparse-README.md deleted file mode 100644 index d08ccf1..0000000 --- a/lib/nl/optparse-README.md +++ /dev/null @@ -1,161 +0,0 @@ -optparse-js -=========== - -Optparse-js is a command line option parser for Javascript. It's slightly based on Ruby's implementation optparse but with some differences (different languages has different needs) such as custom parsers. - -All examples in this readme is using [Node.js](http://nodejs.org/). How ever, the library works with all kinds of Javascript implementations. - - -QUICK START ------------ - -The library defines one class, the OptionParser class. The class constructor takes one single argument, a list with a set of rules. Here is a quick example: - - // Import the sys library - var sys = require('sys'); - - // Import the optparse library. - var optparse = require('optparse'); - - // Define an option called ´´help´´. We give it a quick alias named ´´-h´´ - // and a quick help text. - var switches = [ - ['-h', '--help', 'Shows help sections'] - ]; - - // Create a new OptionParser. - var parser = new optparse.OptionParser(switches); - - // Hook the help option. The callback will be executed when the OptionParser - // hits the switch ´´-h´´ or ´´--help´´. Each representatio - parser.on('help', function() { - sys.puts('Help'); - }); - - - -DEFINING RULES --------------- -The OptionParser constructor takes an Array with rules. Each rule is represented by an array (tuple) of two or three values. A typical rule definition may look like this: - - ['-h', '--help', 'Print this help'] - - -The first value is optional, and represents an alias for the long-named switch (the second value, in this case ´´--help´´). - -The second argument is the actual rule. The rule must start with a double dash followed by a switch name (in this case ´help´). The OptionParser also supports special option arguments. Define an option argument in the rule by adding a named argument after the leading double dash and switch name (E.G '--port-number PORT_NUMBER'). The argument is then parsed to the option handler. To define an optional option argument, just add a braces around argument in the rule (E.G '--port-number [PORT_NUMBER]). The OptionParser also supports filter. More on that in in the section called ´Option Filters´. - -The third argument is an optional rule description. - - -OPTION FILTERS --------------- -Filters is a neat feature that let you filter option arguments. The OptionParser itself as already a set of built-in common filter's. These are: - -- NUMBER, supports both decimal and hexadecimal numbers. -- DATE, filters arguments that matches YYYY-MM-DD. -- EMAIL, filters arguments that matches my@email.com. - -It's simple to use any of the filter above in your rule-set. Here is a quick example how to filter number: - - var rules = [ - ['--first-option NUMBER', 'Takes a number as argument'], - ['--second-option [NUMBER]', 'Takes an optional number as argument'] - ] - -You can add your own set of filter by calling the *parser_instance.filter* method: - - parser.filter('single_char', function(value) { - if(value.length != 1) throw "Filter mismatch."; - return value; - }); - - -OPTION PARSER -------------- -The OptionParser class has the following properties and methods: - -### string banner -An optional usage banner. This text is included when calling ´´toString´´. Default value is: "Usage: [Options]". - - -### string options_title -An optional title for the options list. This text is included when calling ´´toString´´. Default value is: "Available options:". - - -### function on(switch_or_arg_index, callback) -Add's a callback for a switch or an argument (defined by index). Switch hooks MUST be typed witout the leading ´´--´´. This example show how to hook a switch: - - parser.on('help', function(optional_argument) { - // Show help section - }); - -And this example show how to hook an argument (an option without the leading - or --): - - parser.on(0, function(opt) { - puts('The first non-switch option is:' + opt); - }); - -It's also possible to define a default handler. The default handler is called when no rule's are meet. Here is an example how to add a ´default handler´: - - parser.on(function(opt) { - puts('No handler was defined for option:' + opt); - }); - -Use the wildcard handler to build a custom ´´on´´ handler. - - parser.on('*', function(opt, value) { - puts('option=' + opt + ', value=' + value); - }); - -### function filter(name, callback) -Adds a new filter extension to the OptionParser instance. The first argument is the name of the filter (trigger). The second argument is the actual filter See the ´OPTION FILTERS´ section for more info. - -It's possible to override the default filters by passing the value "_DEFAULT" to the ´´name´´ argument. The name of the filter is automatically transformed into -upper case. - - -### function halt([callback]) -Interrupt's further parsing. This function should be called from an ´on´ -callbacks, to cancel the parsing. This can be useful when the program should ignore all other arguments (when displaying help or version information). - -The function also takes an optional callback argument. If the callback argument is specified, a ´halt´ callback will be added (instead of executing the ´halt´ command). - -Here is an example how to add an ´on_halt´ callback: - - parser.halt(function() { - puts('An option callback interupted the parser'); - }); - - -### function parse(arguments) -Start's parsing of arguments. This should be the last thing you do. - - -### function options() -Returns an Array with all defined option rules - - -### function toString() -Returns a string representation of this OptionParser instance (a formatted help section). - - -MORE EXAMPLES -------------- -See examples/nodejs-test.js and examples/browser-test-html for more info how to -use the script. - - -SUGGESTIONS ------------ -All comments in how to improve this library is very welcome. Feel free post suggestions to the [Issue tracker](http://github.com/jfd/optparse-js/issues), or even better, fork the repository to implement your own features. - - -LICENSE -------- -Released under a MIT-style license. - - -COPYRIGHT ---------- -Copyright (c) 2009 Johan Dahlberg - diff --git a/lib/nl/optparse.js b/lib/nl/optparse.js deleted file mode 100644 index 37e3ee8..0000000 --- a/lib/nl/optparse.js +++ /dev/null @@ -1,309 +0,0 @@ -// Optparse.js 1.0.2 - Option Parser for Javascript -// -// Copyright (c) 2009 Johan Dahlberg -// -// See README.md for license. -// -var optparse = {}; -try{ optparse = exports } catch(e) {}; // Try to export the lib for node.js -(function(self) { -var VERSION = '1.0.2'; -var LONG_SWITCH_RE = /^--\w/; -var SHORT_SWITCH_RE = /^-\w/; -var NUMBER_RE = /^(0x[A-Fa-f0-9]+)|([0-9]+\.[0-9]+)|(\d+)$/; -var DATE_RE = /^\d{4}-(0[0-9]|1[0,1,2])-([0,1,2][0-9]|3[0,1])$/; -var EMAIL_RE = /^([0-9a-zA-Z]+([_.-]?[0-9a-zA-Z]+)*@[0-9a-zA-Z]+[0-9,a-z,A-Z,.,-]*(.){1}[a-zA-Z]{2,4})+$/; -var EXT_RULE_RE = /(\-\-[\w_-]+)\s+([\w\[\]_-]+)|(\-\-[\w_-]+)/; -var ARG_OPTIONAL_RE = /\[(.+)\]/; - -// The default switch argument filter to use, when argument name doesnt match -// any other names. -var DEFAULT_FILTER = '_DEFAULT'; -var PREDEFINED_FILTERS = {}; - -// The default switch argument filter. Parses the argument as text. -function filter_text(value) { - return value; -} - -// Switch argument filter that expects an integer, HEX or a decimal value. An -// exception is throwed if the criteria is not matched. -// Valid input formats are: 0xFFFFFFF, 12345 and 1234.1234 -function filter_number(value) { - var m = NUMBER_RE(value); - if(m == null) throw OptError('Expected a number representative'); - if(m[1]) { - // The number is in HEX format. Convert into a number, then return it - return parseInt(m[1], 16); - } else { - // The number is in regular- or decimal form. Just run in through - // the float caster. - return parseFloat(m[2] || m[3]); - } -}; - -// Switch argument filter that expects a Date expression. The date string MUST be -// formated as: "yyyy-mm-dd" An exception is throwed if the criteria is not -// matched. An DATE object is returned on success. -function filter_date(value) { - var m = DATE_RE(value); - if(m == null) throw OptError('Expected a date representation in the "yyyy-mm-dd" format.'); - return new Date(parseInt(m[0]), parseInt(m[1]), parseInt(m[2])); -}; - -// Switch argument filter that expects an email address. An exception is throwed -// if the criteria doesn`t match. -function filter_email(value) { - var m = EMAIL_RE(value); - if(m == null) throw OptError('Excpeted an email address.'); - return m[1]; -} - -// Register all predefined filters. This dict is used by each OptionParser -// instance, when parsing arguments. Custom filters can be added to the parser -// instance by calling the "add_filter" -method. -PREDEFINED_FILTERS[DEFAULT_FILTER] = filter_text; -PREDEFINED_FILTERS['TEXT'] = filter_text; -PREDEFINED_FILTERS['NUMBER'] = filter_number; -PREDEFINED_FILTERS['DATE'] = filter_date; -PREDEFINED_FILTERS['EMAIL'] = filter_email; - -// Buildes rules from a switches collection. The switches collection is defined -// when constructing a new OptionParser object. -function build_rules(filters, arr) { - var rules = []; - for(var i=0; i> value means that the switch does -// not take anargument. -function build_rule(filters, short, expr, desc) { - var optional, filter; - var m = expr.match(EXT_RULE_RE); - if(m == null) throw OptError('The switch is not well-formed.'); - var long = m[1] || m[3]; - if(m[2] != undefined) { - // A switch argument is expected. Check if the argument is optional, - // then find a filter that suites. - var optional_match = ARG_OPTIONAL_RE(m[2]); - var filter_name = optional_match === null ? m[2] : optional_match[1]; - optional = optional_match !== null; - filter = filters[filter_name]; - if(filter === undefined) filter = filters[DEFAULT_FILTER]; - } - return { - name: long.substr(2), - short: short, - long: long, - decl: expr, - desc: desc, - optional_arg: optional, - filter: filter - } -} - -// Loop's trough all elements of an array and check if there is valid -// options expression within. An valid option is a token that starts -// double dashes. E.G. --my_option -function contains_expr(arr) { - if(!arr || !arr.length) return false; - var l = arr.length; - while(l-- > 0) if(LONG_SWITCH_RE(arr[l])) return true; - return false; -} - -// Extends destination object with members of source object -function extend(dest, src) { - var result = dest; - for(var n in src) { - result[n] = src[n]; - } - return result; -} - -// Appends spaces to match specified number of chars -function spaces(arg1, arg2) { - var l, builder = []; - if(arg1.constructor === Number) { - l = arg1; - } else { - if(arg1.length == arg2) return arg1; - l = arg2 - arg1.length; - builder.push(arg1); - } - while(l-- > 0) builder.push(' '); - return builder.join(''); -} - -// Create a new Parser object that can be used to parse command line arguments. -// -// -function Parser(rules) { - return new OptionParser(rules); -} - -// Creates an error object with specified error message. -function OptError(msg) { - return new function() { - this.msg = msg; - this.toString = function() { - return this.msg; - } - } -} - -function OptionParser(rules) { - this.banner = 'Usage: [Options]'; - this.options_title = 'Available options:' - this._rules = rules; - this._halt = false; - this.filters = extend({}, PREDEFINED_FILTERS); - this.on_args = {}; - this.on_switches = {}; - this.on_halt = function() {}; - this.default_handler = function() {}; -} - -OptionParser.prototype = { - - // Adds args and switchs handler. - on: function(value, fn) { - if(value.constructor === Function ) { - this.default_handler = value; - } else if(value.constructor === Number) { - this.on_args[value] = fn; - } else { - this.on_switches[value] = fn; - } - }, - - // Adds a custom filter to the parser. It's possible to override the - // default filter by passing the value "_DEFAULT" to the ´´name´´ - // argument. The name of the filter is automatically transformed into - // upper case. - filter: function(name, fn) { - this.filters[name.toUpperCase()] = fn; - }, - - // Parses specified args. Returns remaining arguments. - parse: function(args) { - var result = [], callback; - var rules = build_rules(this.filters, this._rules); - var tokens = args.concat([]); - while((token = tokens.shift()) && this._halt == false) { - if(LONG_SWITCH_RE(token) || SHORT_SWITCH_RE(token)) { - var arg = undefined; - // The token is a long or a short switch. Get the corresponding - // rule, filter and handle it. Pass the switch to the default - // handler if no rule matched. - for(var i = 0; i < rules.length; i++) { - var rule = rules[i]; - if(rule.long == token || rule.short == token) { - if(rule.filter !== undefined) { - arg = tokens.shift(); - if(!LONG_SWITCH_RE(arg) && !SHORT_SWITCH_RE(arg)) { - try { - arg = rule.filter(arg); - } catch(e) { - throw OptError(token + ': ' + e.toString()); - } - } else if(rule.optional_arg) { - tokens.unshift(arg); - } else { - throw OptError('Expected switch argument.'); - } - } - callback = this.on_switches[rule.name]; - if (!callback) callback = this.on_switches['*']; - if(callback) callback.apply(this, [rule.name, arg]); - break; - } - } - if(i == rules.length) this.default_handler.apply(this, [token]); - } else { - // Did not match long or short switch. Parse the token as a - // normal argument. - callback = this.on_args[result.length]; - result.push(token); - if(callback) callback.apply(this, [token]); - } - } - return this._halt ? this.on_halt.apply(this, []) : result; - }, - - // Returns an Array with all defined option rules - options: function() { - return build_rules(this.filters, this._rules); - }, - - // Add an on_halt callback if argument ´´fn´´ is specified. on_switch handlers can - // call instance.halt to abort the argument parsing. This can be useful when - // displaying help or version information. - halt: function(fn) { - this._halt = fn === undefined - if(fn) this.on_halt = fn; - }, - - // Returns a string representation of this OptionParser instance. - toString: function() { - var builder = [this.banner, '', this.options_title], - shorts = false, longest = 0, rule; - var rules = build_rules(this.filters, this._rules); - for(var i = 0; i < rules.length; i++) { - rule = rules[i]; - // Quick-analyze the options. - if(rule.short) shorts = true; - if(rule.decl.length > longest) longest = rule.decl.length; - } - for(var i = 0; i < rules.length; i++) { - var text; - rule = rules[i]; - if(shorts) { - if(rule.short) text = spaces(2) + rule.short + ', '; - else text = spaces(6); - } - text += spaces(rule.decl, longest) + spaces(3); - text += rule.desc; - builder.push(text); - } - return builder.join('\n'); - } -} - -self.VERSION = VERSION; -self.OptionParser = OptionParser; - -})(optparse); \ No newline at end of file diff --git a/nl.js b/nl.js index d3b9096..b196db8 100755 --- a/nl.js +++ b/nl.js @@ -26,9 +26,6 @@ */ /*jslint sub:true */ -/*globals __dirname */ - -require.paths.unshift(__dirname); var options = require('./lib/nl/options'); options.process(); diff --git a/package.json b/package.json index 1038134..b800ede 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,7 @@ "keywords": ["testing", "load testing", "http"], "homepage": "https://github.com/benschmaus/nodeload", "engines": { - "node": "0.4" + "node": ">=0.4" }, "contributors": [ "Benjamin Schmaus ", @@ -38,6 +38,7 @@ "expresso": ">=0.7.7" }, "dependencies": { + "optparse": "1.0.3" }, "licenses": [ { diff --git a/scripts/jsmin.js b/scripts/jsmin.js index 8addf03..9a7e86a 100755 --- a/scripts/jsmin.js +++ b/scripts/jsmin.js @@ -366,11 +366,10 @@ function jsmin(input, level, comment) { } // Make jsmin a runnable application -var sys = require('sys'); if (process.argv.length == 3) { // Read from file and write to stdout var fs = require('fs'); - input = fs.readFile(process.argv[2], 'binary', function(err, data) { sys.puts(data) }); + input = fs.readFile(process.argv[2], 'binary', function(err, data) { console.log(data) }); } else { // Read from stdin and write to stdout var stdin = process.openStdin(); @@ -379,6 +378,6 @@ if (process.argv.length == 3) { input += chunk; }); stdin.on('end', function () { - sys.puts(jsmin(input)); + console.log(jsmin(input)); }); } \ No newline at end of file