1
0
mirror of https://github.com/mgerb/mywebsite synced 2026-01-12 10:52:47 +00:00

updated package.json

This commit is contained in:
2016-01-04 12:25:28 -05:00
parent 3443c97de4
commit 80ca24a715
1168 changed files with 73752 additions and 26424 deletions

3
node_modules/event-stream/.gitmodules generated vendored Normal file
View File

@@ -0,0 +1,3 @@
[submodule "test"]
path = test
url = git@github.com:dominictarr/event-stream_tests.git

3
node_modules/event-stream/.npmignore generated vendored Normal file
View File

@@ -0,0 +1,3 @@
node_modules
node_modules/*
npm_debug.log

22
node_modules/event-stream/LICENCE generated vendored Normal file
View File

@@ -0,0 +1,22 @@
Copyright (c) 2011 Dominic Tarr
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.

25
node_modules/event-stream/examples/pretty.js generated vendored Normal file
View File

@@ -0,0 +1,25 @@
var inspect = require('util').inspect
if(!module.parent) {
var es = require('..') //load event-stream
es.pipe( //pipe joins streams together
process.openStdin(), //open stdin
es.split(), //split stream to break on newlines
es.map(function (data, callback) {//turn this async function into a stream
var j
try {
j = JSON.parse(data) //try to parse input into json
} catch (err) {
return callback(null, data) //if it fails just pass it anyway
}
callback(null, inspect(j)) //render it nicely
}),
process.stdout // pipe it to stdout !
)
}
// run this
//
// curl -sS registry.npmjs.org/event-stream | node pretty.js
//

504
node_modules/event-stream/index.js generated vendored Normal file
View File

@@ -0,0 +1,504 @@
//filter will reemit the data if cb(err,pass) pass is truthy
// reduce is more tricky
// maybe we want to group the reductions or emit progress updates occasionally
// the most basic reduce just emits one 'data' event after it has recieved 'end'
var Stream = require('stream').Stream
, es = exports
es.Stream = Stream //re-export Stream from core
// writable stream, collects all events into an array
// and calls back when 'end' occurs
// mainly I'm using this to test the other functions
es.writeArray = function (done) {
if ('function' !== typeof done)
throw new Error('function writeArray (done): done must be function')
var a = new Stream ()
, array = []
a.write = function (l) {
array.push(l)
}
a.end = function () {
done(null, array)
}
a.writable = true
a.readable = false
return a
}
//return a Stream that reads the properties of an object
//respecting pause() and resume()
es.readArray = function (array) {
var stream = new Stream()
, i = 0
, paused = false
stream.readable = true
stream.writable = false
if(!Array.isArray(array))
throw new Error('event-stream.read expects an array')
stream.resume = function () {
paused = false
var l = array.length
while(i < l && !paused) {
stream.emit('data', array[i++])
}
if(i == l)
stream.emit('end'), stream.readible = false
}
process.nextTick(stream.resume)
stream.pause = function () {
paused = true
}
return stream
}
//
// readable (asyncFunction)
// return a stream that calls an async function while the stream is not paused.
//
// the function must take: (count, callback) {...
//
es.readable = function (func, continueOnError) {
var stream = new Stream()
, i = 0
, paused = false
, ended = false
, reading = false
stream.readable = true
stream.writable = false
if('function' !== typeof func)
throw new Error('event-stream.readable expects async function')
stream.on('end', function () { ended = true })
function get (err, data) {
if(err) {
stream.emit('error', err)
if(!continueOnError) stream.emit('end')
} else if (arguments.length > 1)
stream.emit('data', data)
process.nextTick(function () {
if(ended || paused || reading) return
try {
reading = true
func.call(stream, i++, function () {
reading = false
get.apply(null, arguments)
})
} catch (err) {
stream.emit('error', err)
}
})
}
stream.resume = function () {
paused = false
get()
}
process.nextTick(get)
stream.pause = function () {
paused = true
}
return stream
}
//create an event stream and apply function to each .write
//emitting each response as data
//unless it's an empty callback
es.map = function (mapper) {
var stream = new Stream()
, inputs = 0
, outputs = 0
, ended = false
, paused = false
stream.writable = true
stream.readable = true
stream.write = function () {
inputs ++
var args = [].slice.call(arguments)
, r
, inNext = false
function next (err) {
inNext = true
outputs ++
var args = [].slice.call(arguments)
if(err) {
args.unshift('error')
return inNext = false, stream.emit.apply(stream, args)
}
args.shift() //drop err
if (args.length){
args.unshift('data')
r = stream.emit.apply(stream, args)
}
if(inputs == outputs) {
if(paused) stream.emit('drain') //written all the incoming events
paused = false
if(ended)
stream.end()
}
inNext = false
}
args.push(next)
try {
//catch sync errors and handle them like async errors
var written = mapper.apply(null,args)
if(written === false) paused = true
return written
} catch (err) {
//if the callback has been called syncronously, and the error
//has occured in an listener, throw it again.
if(inNext)
throw err
next(err)
return true
}
}
stream.end = function () {
var args = [].slice.call(arguments)
//if end was called with args, write it,
ended = true //write will emit 'end' if ended is true
if(args.length)
return stream.write.apply(emitter, args)
else if (inputs == outputs) //wait for processing
stream.emit('end')
}
return stream
}
//
// map sync
//
es.mapSync = function (sync) {
return es.map(function () {
var args = [].slice.call(arguments)
, callback = args.pop()
callback(null, sync.apply(null, args))
})
}
//
// log just print out what is coming through the stream, for debugging
//
es.log = function (name) {
return es.map(function () {
var args = [].slice.call(arguments)
var cb = args.pop()
if(name) args.slice().unshift(name)
console.error.apply(null, args)
args.unshift(null)
cb.apply(null, args)
})
}
//
// combine multiple streams together so that they act as a single stream
//
es.pipe = es.connect = function () {
var streams = [].slice.call(arguments)
, first = streams[0]
, last = streams[streams.length - 1]
, thepipe = es.duplex(first, last)
if(streams.length == 1)
return streams[0]
else if (!streams.length)
throw new Error('connect called with empty args')
//pipe all the streams together
function recurse (streams) {
if(streams.length < 2)
return
streams[0].pipe(streams[1])
recurse(streams.slice(1))
}
recurse(streams)
function onerror () {
var args = [].slice.call(arguments)
args.unshift('error')
thepipe.emit.apply(thepipe, args)
}
streams.forEach(function (stream) {
stream.on('error', onerror)
})
return thepipe
}
//
// child -- pipe through a child process
//
es.child = function (child) {
return es.duplex(child.stdin, child.stdout)
}
//
// duplex -- pipe into one stream and out another
//
es.duplex = function (writer, reader) {
var thepipe = new Stream()
thepipe.__defineGetter__('writable', function () { return writer.writable })
thepipe.__defineGetter__('readable', function () { return reader.readable })
;['write', 'end', 'close'].forEach(function (func) {
thepipe[func] = function () {
return writer[func].apply(writer, arguments)
}
})
;['resume', 'pause'].forEach(function (func) {
thepipe[func] = function () {
thepipe.emit(func)
if(reader[func])
return reader[func].apply(reader, arguments)
else
reader.emit(func)
}
})
;['data', 'close'].forEach(function (event) {
reader.on(event, function () {
var args = [].slice.call(arguments)
args.unshift(event)
thepipe.emit.apply(thepipe, args)
})
})
//only emit end once
var ended = false
reader.on('end', function () {
if(ended) return
ended = true
var args = [].slice.call(arguments)
args.unshift('end')
thepipe.emit.apply(thepipe, args)
})
return thepipe
}
es.split = function (matcher) {
var stream = new Stream()
, soFar = ''
if (!matcher)
matcher = '\n'
stream.writable = true
stream.write = function (buffer) {
buffer = buffer.toString()
var l = buffer.length
, i = 0
while (i < l) {
var c = buffer[i].toString()
soFar += c
if (c == matcher) {
var n = soFar;
soFar = ''
this.emit('data', n)
}
i++
}
}
stream.end = function () {
stream.emit('data', soFar)
stream.emit('end')
}
return stream
}
//
// gate
//
// while the gate is shut(), buffer incoming.
//
// if gate is open() stream like normal.
//
// currently, when opened, this will emit all data unless it is shut again
// if downstream pauses it will still write, i'd like to make it respect pause,
// but i'll need a test case first.
es.gate = function (shut) {
var stream = new Stream()
, queue = []
, ended = false
shut = (shut === false ? false : true) //default to shut
// console.error('SHUT?', shut)
stream.writable = true
stream.readable = true
stream.isShut = function () { return shut }
stream.shut = function () { shut = true }
stream.open = function () { shut = false; maybe() }
function maybe () {
// console.error('maybe', queue.length, shut)
while(queue.length && !shut) {
var args = queue.shift()
args.unshift('data')
stream.emit.apply(stream, args)
}
stream.emit('drain')
if(ended && !shut)
stream.emit('end')
}
stream.write = function () {
var args = [].slice.call(arguments)
queue.push(args)
// console.error(queue)
if (shut) return false //pause up stream pipes
maybe()
}
stream.end = function () {
ended = true
if (!queue.length)
stream.emit('end')
}
return stream
}
//
// parse
//
es.parse = function () {
return es.mapSync(function (e){
return JSON.parse(e.toString())
})
}
//
// stringify
//
es.stringify = function () {
return es.mapSync(function (e){
return JSON.stringify(e) + '\n'
})
}
//
// helper to make your module into a unix pipe
// simply add
//
// if(!module.parent)
// require('event-stream').pipable(asyncFunctionOrStreams)
//
// asyncFunctionOrStreams may be one or more Streams or if it is a function,
// it will be automatically wrapped in es.map
//
// then pipe stuff into from the command line!
//
// curl registry.npmjs.org/event-stream | node hello-pipeable.js | grep whatever
//
// etc!
//
// also, start pipeable running as a server!
//
// > node hello-pipeable.js --port 44444
//
var setup = function (args) {
return args.map(function (f) {
var x = f()
if('function' === typeof x)
return es.map(x)
return x
})
}
es.pipeable = function () {
var opts = require('optimist').argv
var args = [].slice.call(arguments)
if(opts.h || opts.help) {
var name = process.argv[1]
console.error([
'Usage:',
'',
'node ' + name + ' [options]',
' --port PORT turn this stream into a server',
' --host HOST host of server (localhost is default)',
' --protocol protocol http|net will require(protocol).createServer(...',
' --help display this message',
'',
' if --port is not set, will stream input from stdin',
'',
'also, pipe from or to files:',
'',
' node '+name+ ' < file #pipe from file into this stream',
' node '+name+ ' < infile > outfile #pipe from file into this stream',
'',
].join('\n'))
} else if (!opts.port) {
var streams = setup(args)
streams.unshift(es.split())
//streams.unshift()
streams.push(process.stdout)
var c = es.connect.apply(null, streams)
process.openStdin().pipe(c) //there
return c
} else {
opts.host = opts.host || 'localhost'
opts.protocol = opts.protocol || 'http'
var protocol = require(opts.protocol)
var server = protocol.createServer(function (instream, outstream) {
var streams = setup(args)
streams.unshift(es.split())
streams.unshift(instream)
streams.push(outstream || instream)
es.pipe.apply(null, streams)
})
server.listen(opts.port, opts.host)
console.error(process.argv[1] +' is listening for "' + opts.protocol + '" on ' + opts.host + ':' + opts.port)
}
}

View File

@@ -0,0 +1,4 @@
lib-cov/*
*.swp
*.swo
node_modules

View File

@@ -0,0 +1,21 @@
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.

View File

@@ -0,0 +1,474 @@
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).
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 ] }
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).

View File

@@ -0,0 +1,10 @@
#!/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 ? '.' : '')
);

View File

@@ -0,0 +1,7 @@
#!/usr/bin/env node
var argv = require('optimist')
.boolean(['x','y','z'])
.argv
;
console.dir([ argv.x, argv.y, argv.z ]);
console.dir(argv._);

View File

@@ -0,0 +1,7 @@
#!/usr/bin/env node
var argv = require('optimist')
.boolean('v')
.argv
;
console.dir(argv.v);
console.dir(argv._);

View File

@@ -0,0 +1,8 @@
#!/usr/bin/env node
var argv = require('optimist')
.default({ x : 10, y : 10 })
.argv
;
console.log(argv.x + argv.y);

View File

@@ -0,0 +1,7 @@
#!/usr/bin/env node
var argv = require('optimist')
.default('x', 10)
.default('y', 10)
.argv
;
console.log(argv.x + argv.y);

View File

@@ -0,0 +1,8 @@
#!/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);

View File

@@ -0,0 +1,20 @@
#!/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);
});

View File

@@ -0,0 +1,29 @@
#!/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));
});

View File

@@ -0,0 +1,29 @@
#!/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));
});

View File

@@ -0,0 +1,4 @@
#!/usr/bin/env node
var argv = require('optimist').argv;
console.log('(%d,%d)', argv.x, argv.y);
console.log(argv._);

View File

@@ -0,0 +1,2 @@
#!/usr/bin/env node
console.dir(require('optimist').argv);

View File

@@ -0,0 +1,3 @@
#!/usr/bin/env node
var argv = require('optimist').argv;
console.log('(%d,%d)', argv.x, argv.y);

View File

@@ -0,0 +1,11 @@
#!/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' ]
*/

View File

@@ -0,0 +1,19 @@
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);

View File

@@ -0,0 +1,10 @@
#!/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');
}

View File

@@ -0,0 +1,457 @@
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 (opt.default) 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;
if (key in argv && !flags.bools[key]) {
if (!Array.isArray(argv[key])) {
argv[key] = [ argv[key] ];
}
argv[key].push(value);
}
else {
argv[key] = 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]) {
setArg(key, next);
i++;
}
else if (flags.bools[key] && /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]) {
setArg(key, args[i+1]);
i++;
}
else if (args[i+1] && flags.bools[key] && /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 (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;
};

View File

@@ -0,0 +1,98 @@
{
"_args": [
[
"optimist@0.2",
"/home/mywebsite/node_modules/event-stream"
]
],
"_defaultsLoaded": true,
"_engineSupported": true,
"_from": "optimist@>=0.2.0 <0.3.0",
"_id": "optimist@0.2.8",
"_inCache": true,
"_installable": true,
"_location": "/event-stream/optimist",
"_nodeVersion": "v0.4.12",
"_npmUser": {
"email": "mail@substack.net",
"name": "substack"
},
"_npmVersion": "1.0.99",
"_phantomChildren": {},
"_requested": {
"name": "optimist",
"raw": "optimist@0.2",
"rawSpec": "0.2",
"scope": null,
"spec": ">=0.2.0 <0.3.0",
"type": "range"
},
"_requiredBy": [
"/event-stream"
],
"_resolved": "https://registry.npmjs.org/optimist/-/optimist-0.2.8.tgz",
"_shasum": "e981ab7e268b457948593b55674c099a815cac31",
"_shrinkwrap": null,
"_spec": "optimist@0.2",
"_where": "/home/mywebsite/node_modules/event-stream",
"author": {
"email": "mail@substack.net",
"name": "James Halliday",
"url": "http://substack.net"
},
"bugs": {
"url": "https://github.com/substack/node-optimist/issues"
},
"dependencies": {
"wordwrap": ">=0.0.1 <0.1.0"
},
"description": "Light-weight option parsing with an argv hash. No optstrings attached.",
"devDependencies": {
"expresso": "0.7.x",
"hashish": "0.0.x"
},
"directories": {
"example": "examples",
"lib": ".",
"test": "test"
},
"dist": {
"shasum": "e981ab7e268b457948593b55674c099a815cac31",
"tarball": "http://registry.npmjs.org/optimist/-/optimist-0.2.8.tgz"
},
"engine": {
"node": ">=0.4"
},
"engines": {
"node": "*"
},
"homepage": "https://github.com/substack/node-optimist#readme",
"keywords": [
"args",
"argument",
"cli",
"command",
"option",
"parser",
"parsing"
],
"license": "MIT/X11",
"main": "./index.js",
"maintainers": [
{
"name": "substack",
"email": "mail@substack.net"
}
],
"name": "optimist",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/substack/node-optimist.git"
},
"scripts": {
"test": "expresso"
},
"version": "0.2.8"
}

View File

@@ -0,0 +1,66 @@
var spawn = require('child_process').spawn;
var assert = require('assert');
exports.dotSlashEmpty = function () {
testCmd('./bin.js', []);
};
exports.dotSlashArgs = function () {
testCmd('./bin.js', [ 'a', 'b', 'c' ]);
};
exports.nodeEmpty = function () {
testCmd('node bin.js', []);
};
exports.nodeArgs = function () {
testCmd('node bin.js', [ 'x', 'y', 'z' ]);
};
exports.whichNodeEmpty = function () {
var which = spawn('which', ['node']);
which.stdout.on('data', function (buf) {
testCmd(buf.toString().trim() + ' bin.js', []);
});
which.stderr.on('data', function (err) {
assert.fail(err.toString());
});
};
exports.whichNodeArgs = function () {
var which = spawn('which', ['node']);
which.stdout.on('data', function (buf) {
testCmd(buf.toString().trim() + ' bin.js', [ 'q', 'r' ]);
});
which.stderr.on('data', function (err) {
assert.fail(err.toString());
});
};
function testCmd (cmd, args) {
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) {
assert.fail(err.toString());
});
bin.stdout.on('data', function (buf) {
clearTimeout(to);
var _ = JSON.parse(buf.toString());
assert.eql(_.map(String), args.map(String));
});
}

View File

@@ -0,0 +1,2 @@
#!/usr/bin/env node
console.log(JSON.stringify(process.argv));

View File

@@ -0,0 +1,3 @@
#!/usr/bin/env node
var argv = require('../../index').argv
console.log(JSON.stringify(argv._));

View File

@@ -0,0 +1,304 @@
var optimist = require('../index');
var assert = require('assert');
var path = require('path');
var localExpresso = path.normalize(
__dirname + '/../node_modules/.bin/expresso'
);
var expresso = process.argv[1] === localExpresso
? 'node ./node_modules/.bin/expresso'
: 'expresso'
;
exports['short boolean'] = function () {
var parse = optimist.parse([ '-b' ]);
assert.eql(parse, { b : true, _ : [], $0 : expresso });
assert.eql(typeof parse.b, 'boolean');
};
exports['long boolean'] = function () {
assert.eql(
optimist.parse([ '--bool' ]),
{ bool : true, _ : [], $0 : expresso }
);
};
exports.bare = function () {
assert.eql(
optimist.parse([ 'foo', 'bar', 'baz' ]),
{ _ : [ 'foo', 'bar', 'baz' ], $0 : expresso }
);
};
exports['short group'] = function () {
assert.eql(
optimist.parse([ '-cats' ]),
{ c : true, a : true, t : true, s : true, _ : [], $0 : expresso }
);
};
exports['short group next'] = function () {
assert.eql(
optimist.parse([ '-cats', 'meow' ]),
{ c : true, a : true, t : true, s : 'meow', _ : [], $0 : expresso }
);
};
exports['short capture'] = function () {
assert.eql(
optimist.parse([ '-h', 'localhost' ]),
{ h : 'localhost', _ : [], $0 : expresso }
);
};
exports['short captures'] = function () {
assert.eql(
optimist.parse([ '-h', 'localhost', '-p', '555' ]),
{ h : 'localhost', p : 555, _ : [], $0 : expresso }
);
};
exports['long capture sp'] = function () {
assert.eql(
optimist.parse([ '--pow', 'xixxle' ]),
{ pow : 'xixxle', _ : [], $0 : expresso }
);
};
exports['long capture eq'] = function () {
assert.eql(
optimist.parse([ '--pow=xixxle' ]),
{ pow : 'xixxle', _ : [], $0 : expresso }
);
};
exports['long captures sp'] = function () {
assert.eql(
optimist.parse([ '--host', 'localhost', '--port', '555' ]),
{ host : 'localhost', port : 555, _ : [], $0 : expresso }
);
};
exports['long captures eq'] = function () {
assert.eql(
optimist.parse([ '--host=localhost', '--port=555' ]),
{ host : 'localhost', port : 555, _ : [], $0 : expresso }
);
};
exports['mixed short bool and capture'] = function () {
assert.eql(
optimist.parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]),
{
f : true, p : 555, h : 'localhost',
_ : [ 'script.js' ], $0 : expresso,
}
);
};
exports['short and long'] = function () {
assert.eql(
optimist.parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]),
{
f : true, p : 555, h : 'localhost',
_ : [ 'script.js' ], $0 : expresso,
}
);
};
exports.no = function () {
assert.eql(
optimist.parse([ '--no-moo' ]),
{ moo : false, _ : [], $0 : expresso }
);
};
exports.multi = function () {
assert.eql(
optimist.parse([ '-v', 'a', '-v', 'b', '-v', 'c' ]),
{ v : ['a','b','c'], _ : [], $0 : expresso }
);
};
exports.comprehensive = function () {
assert.eql(
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 : expresso
}
);
};
exports.nums = function () {
var argv = optimist.parse([
'-x', '1234',
'-y', '5.67',
'-z', '1e7',
'-w', '10f',
'--hex', '0xdeadbeef',
'789',
]);
assert.eql(argv, {
x : 1234,
y : 5.67,
z : 1e7,
w : '10f',
hex : 0xdeadbeef,
_ : [ 789 ],
$0 : expresso
});
assert.eql(typeof argv.x, 'number');
assert.eql(typeof argv.y, 'number');
assert.eql(typeof argv.z, 'number');
assert.eql(typeof argv.w, 'string');
assert.eql(typeof argv.hex, 'number');
assert.eql(typeof argv._[0], 'number');
};
exports['flag boolean'] = function () {
var parse = optimist([ '-t', 'moo' ]).boolean(['t']).argv;
assert.eql(parse, { t : true, _ : [ 'moo' ], $0 : expresso });
assert.eql(typeof parse.t, 'boolean');
};
exports['flag boolean value'] = function () {
var parse = optimist(['--verbose', 'false', 'moo', '-t', 'true'])
.boolean(['t', 'verbose']).default('verbose', true).argv;
assert.eql(parse, {
verbose: false,
t: true,
_: ['moo'],
$0 : expresso
});
assert.eql(typeof parse.verbose, 'boolean');
assert.eql(typeof parse.t, 'boolean');
};
exports['flag boolean default false'] = function () {
var parse = optimist(['moo'])
.boolean(['t', 'verbose'])
.default('verbose', false)
.default('t', false).argv;
assert.eql(parse, {
verbose: false,
t: false,
_: ['moo'],
$0 : expresso
});
assert.eql(typeof parse.verbose, 'boolean');
assert.eql(typeof parse.t, 'boolean');
};
exports['boolean groups'] = function () {
var parse = optimist([ '-x', '-z', 'one', 'two', 'three' ])
.boolean(['x','y','z']).argv;
assert.eql(parse, {
x : true,
y : false,
z : true,
_ : [ 'one', 'two', 'three' ],
$0 : expresso
});
assert.eql(typeof parse.x, 'boolean');
assert.eql(typeof parse.y, 'boolean');
assert.eql(typeof parse.z, 'boolean');
};
exports.strings = function () {
var s = optimist([ '-s', '0001234' ]).string('s').argv.s;
assert.eql(s, '0001234');
assert.eql(typeof s, 'string');
var x = optimist([ '-x', '56' ]).string('x').argv.x;
assert.eql(x, '56');
assert.eql(typeof x, 'string');
};
exports.stringArgs = function () {
var s = optimist([ ' ', ' ' ]).string('_').argv._;
assert.eql(s.length, 2);
assert.eql(typeof s[0], 'string');
assert.eql(s[0], ' ');
assert.eql(typeof s[1], 'string');
assert.eql(s[1], ' ');
};
exports.slashBreak = function () {
assert.eql(
optimist.parse([ '-I/foo/bar/baz' ]),
{ I : '/foo/bar/baz', _ : [], $0 : expresso }
);
assert.eql(
optimist.parse([ '-xyz/foo/bar/baz' ]),
{ x : true, y : true, z : '/foo/bar/baz', _ : [], $0 : expresso }
);
};
exports.alias = function () {
var argv = optimist([ '-f', '11', '--zoom', '55' ])
.alias('z', 'zoom')
.argv
;
assert.equal(argv.zoom, 55);
assert.equal(argv.z, argv.zoom);
assert.equal(argv.f, 11);
};
exports.multiAlias = function () {
var argv = optimist([ '-f', '11', '--zoom', '55' ])
.alias('z', [ 'zm', 'zoom' ])
.argv
;
assert.equal(argv.zoom, 55);
assert.equal(argv.z, argv.zoom);
assert.equal(argv.z, argv.zm);
assert.equal(argv.f, 11);
};
exports['boolean default true'] = function () {
var argv = optimist.options({
sometrue: {
boolean: true,
default: true
}
}).argv;
assert.equal(argv.sometrue, true);
};
exports['boolean default false'] = function () {
var argv = optimist.options({
somefalse: {
boolean: true,
default: false
}
}).argv;
assert.equal(argv.somefalse, false);
};

View File

@@ -0,0 +1,256 @@
var Hash = require('hashish');
var optimist = require('../index');
var assert = require('assert');
exports.usageFail = function () {
var r = checkUsage(function () {
return optimist('-x 10 -z 20'.split(' '))
.usage('Usage: $0 -x NUM -y NUM')
.demand(['x','y'])
.argv;
});
assert.deepEqual(
r.result,
{ x : 10, z : 20, _ : [], $0 : './usage' }
);
assert.deepEqual(
r.errors.join('\n').split(/\n+/),
[
'Usage: ./usage -x NUM -y NUM',
'Options:',
' -x [required]',
' -y [required]',
'Missing required arguments: y',
]
);
assert.deepEqual(r.logs, []);
assert.ok(r.exit);
};
exports.usagePass = function () {
var r = checkUsage(function () {
return optimist('-x 10 -y 20'.split(' '))
.usage('Usage: $0 -x NUM -y NUM')
.demand(['x','y'])
.argv;
});
assert.deepEqual(r, {
result : { x : 10, y : 20, _ : [], $0 : './usage' },
errors : [],
logs : [],
exit : false,
});
};
exports.checkPass = function () {
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;
});
assert.deepEqual(r, {
result : { x : 10, y : 20, _ : [], $0 : './usage' },
errors : [],
logs : [],
exit : false,
});
};
exports.checkFail = function () {
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;
});
assert.deepEqual(
r.result,
{ x : 10, z : 20, _ : [], $0 : './usage' }
);
assert.deepEqual(
r.errors.join('\n').split(/\n+/),
[
'Usage: ./usage -x NUM -y NUM',
'You forgot about -y'
]
);
assert.deepEqual(r.logs, []);
assert.ok(r.exit);
};
exports.checkCondPass = function () {
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;
});
assert.deepEqual(r, {
result : { x : 10, y : 20, _ : [], $0 : './usage' },
errors : [],
logs : [],
exit : false,
});
};
exports.checkCondFail = function () {
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;
});
assert.deepEqual(
r.result,
{ x : 10, z : 20, _ : [], $0 : './usage' }
);
assert.deepEqual(
r.errors.join('\n').split(/\n+/).join('\n'),
'Usage: ./usage -x NUM -y NUM\n'
+ 'Argument check failed: ' + checker.toString()
);
assert.deepEqual(r.logs, []);
assert.ok(r.exit);
};
exports.countPass = function () {
var r = checkUsage(function () {
return optimist('1 2 3 --moo'.split(' '))
.usage('Usage: $0 [x] [y] [z] {OPTIONS}')
.demand(3)
.argv;
});
assert.deepEqual(r, {
result : { _ : [ '1', '2', '3' ], moo : true, $0 : './usage' },
errors : [],
logs : [],
exit : false,
});
};
exports.countFail = function () {
var r = checkUsage(function () {
return optimist('1 2 --moo'.split(' '))
.usage('Usage: $0 [x] [y] [z] {OPTIONS}')
.demand(3)
.argv;
});
assert.deepEqual(
r.result,
{ _ : [ '1', '2' ], moo : true, $0 : './usage' }
);
assert.deepEqual(
r.errors.join('\n').split(/\n+/),
[
'Usage: ./usage [x] [y] [z] {OPTIONS}',
'Not enough non-option arguments: got 2, need at least 3',
]
);
assert.deepEqual(r.logs, []);
assert.ok(r.exit);
};
exports.defaultSingles = function () {
var r = checkUsage(function () {
return optimist('--foo 50 --baz 70 --powsy'.split(' '))
.default('foo', 5)
.default('bar', 6)
.default('baz', 7)
.argv
;
});
assert.eql(r.result, {
foo : '50',
bar : 6,
baz : '70',
powsy : true,
_ : [],
$0 : './usage',
});
};
exports.defaultHash = function () {
var r = checkUsage(function () {
return optimist('--foo 50 --baz 70'.split(' '))
.default({ foo : 10, bar : 20, quux : 30 })
.argv
;
});
assert.eql(r.result, {
foo : '50',
bar : 20,
baz : 70,
quux : 30,
_ : [],
$0 : './usage',
});
};
exports.rebase = function () {
assert.equal(
optimist.rebase('/home/substack', '/home/substack/foo/bar/baz'),
'./foo/bar/baz'
);
assert.equal(
optimist.rebase('/home/substack/foo/bar/baz', '/home/substack'),
'../../..'
);
assert.equal(
optimist.rebase('/home/substack/foo', '/home/substack/pow/zoom.txt'),
'../pow/zoom.txt'
);
};
function checkUsage (f) {
var _process = process;
process = Hash.copy(process);
var exit = false;
process.exit = function () { 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 = _process;
console.error = console._error;
console.log = console._log;
return {
errors : errors,
logs : logs,
exit : exit,
result : result,
};
};

0
node_modules/event-stream/out generated vendored Normal file
View File

80
node_modules/event-stream/package.json generated vendored Normal file
View File

@@ -0,0 +1,80 @@
{
"_args": [
[
"event-stream@~0.5",
"/home/mywebsite/node_modules/ps-tree"
]
],
"_defaultsLoaded": true,
"_engineSupported": true,
"_from": "event-stream@>=0.5.0 <0.6.0",
"_id": "event-stream@0.5.3",
"_inCache": true,
"_installable": true,
"_location": "/event-stream",
"_nodeVersion": "v0.4.10",
"_npmUser": {
"email": "dominic.tarr@gmail.com",
"name": "dominictarr"
},
"_npmVersion": "1.0.101",
"_phantomChildren": {
"wordwrap": "0.0.3"
},
"_requested": {
"name": "event-stream",
"raw": "event-stream@~0.5",
"rawSpec": "~0.5",
"scope": null,
"spec": ">=0.5.0 <0.6.0",
"type": "range"
},
"_requiredBy": [
"/ps-tree"
],
"_resolved": "https://registry.npmjs.org/event-stream/-/event-stream-0.5.3.tgz",
"_shasum": "b77b9309f7107addfeab63f0c0eafd8db0bd8c1c",
"_shrinkwrap": null,
"_spec": "event-stream@~0.5",
"_where": "/home/mywebsite/node_modules/ps-tree",
"author": {
"email": "dominic.tarr@gmail.com",
"name": "Dominic Tarr",
"url": "http://bit.ly/dominictarr"
},
"bugs": {
"url": "https://github.com/dominictarr/event-stream/issues"
},
"dependencies": {
"optimist": "0.2"
},
"description": "construct pipes of streams of events",
"devDependencies": {
"asynct": "1",
"d-utils": "2.3",
"it-is": "1"
},
"directories": {},
"dist": {
"shasum": "b77b9309f7107addfeab63f0c0eafd8db0bd8c1c",
"tarball": "http://registry.npmjs.org/event-stream/-/event-stream-0.5.3.tgz"
},
"engines": {
"node": "*"
},
"homepage": "http://github.com/dominictarr/event-stream",
"maintainers": [
{
"name": "dominictarr",
"email": "dominic.tarr@gmail.com"
}
],
"name": "event-stream",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/dominictarr/event-stream.git"
},
"version": "0.5.3"
}

358
node_modules/event-stream/readme.markdown generated vendored Normal file
View File

@@ -0,0 +1,358 @@
# EventStream
[Streams](http://nodejs.org/api/streams.html "Stream") are nodes best and most misunderstood idea, and
_<em>EventStream</em>_ is a toolkit to make creating and working with streams <em>easy</em>.
Normally, streams are only used of IO,
but in event stream we send all kinds of objects down the pipe.
If your application's <em>input</em> and <em>output</em> are streams,
shouldn't the <em>throughput</em> be a stream too?
The *EventStream* functions resemble the array functions,
because Streams are like Arrays, but laid out in time, rather than in memory.
<em>All the `event-stream` functions return instances of `Stream`</em>.
Stream API docs: [nodejs.org/api/streams](http://nodejs.org/api/streams.html "Stream")
NOTE: I shall use the term <em>"through stream"</em> to refer to a stream that is writable <em>and</em> readable.
###[simple example](https://github.com/dominictarr/event-stream/blob/master/examples/pretty.js):
``` js
//pretty.js
if(!module.parent) {
var es = require('event-stream')
es.connect( //connect streams together with `pipe`
process.openStdin(), //open stdin
es.split(), //split stream to break on newlines
es.map(function (data, callback) {//turn this async function into a stream
callback(null
, inspect(JSON.parse(data))) //render it nicely
}),
process.stdout // pipe it to stdout !
)
}
```
run it ...
``` bash
curl -sS registry.npmjs.org/event-stream | node pretty.js
```
[test are in event-stream_tests](https://github.com/dominictarr/event-stream_tests)
[node Stream documentation](http://nodejs.org/api/streams.html)
##map (asyncFunction)
Create a through stream from an asyncronous function.
``` js
var es = require('event-stream')
es.map(function (data, callback) {
//transform data
// ...
callback(null, data)
})
```
Each map MUST call the callback. It may callback with data, with an error or with no arguments,
* `callback()` drop this data.
this makes the map work like `filter`,
note:`callback(null,null)` is not the same, and will emit `null`
* `callback(null, newData)` turn data into newData
* `callback(error)` emit an error for this item.
>Note: if a callback is not called, `map` will think that it is still being processed,
>every call must be answered or the stream will not know when to end.
>
>Also, if the callback is called more than once, every call but the first will be ignored.
##readable (asyncFunction)
create a readable stream (that respects pause) from an async function.
while the stream is not paused,
the function will be polled with `(count, callback)`,
and `this` will be the readable stream.
``` js
es.readable(function (count, callback) {
if(streamHasEnded)
return this.emit('end')
//...
this.emit('data', data) //use this way to emit multiple chunks per call.
callback() // you MUST always call the callback eventually.
// the function will not be called again until you do this.
})
```
you can also pass the data and the error to the callback.
you may only call the callback once.
calling the same callback more than once will have no effect.
##readArray (array)
Create a readable stream from an Array.
Just emit each item as a data event, respecting `pause` and `resume`.
``` js
var es = require('event-stream')
, reader = es.readArray([1,2,3])
reader.pipe(...)
```
## writeArray (callback)
create a writeable stream from a callback,
all `data` events are stored in an array, which is passed to the callback when the stream ends.
``` js
var es = require('event-stream')
, reader = es.readArray([1, 2, 3])
, writer = es.writeArray(function (err, array){
//array deepEqual [1, 2, 3]
})
reader.pipe(writer)
```
## split ()
Break up a stream and reassemble it so that each line is a chunk.
Example, read every line in a file ...
``` js
es.connect(
fs.createReadStream(file, {flags: 'r'}),
es.split(),
es.map(function (line, cb) {
//do something with the line
cb(null, line)
})
)
```
## connect (stream1,...,streamN)
Connect multiple Streams together into one stream.
`connect` will return a Stream. This stream will write to the first stream,
and will emit data from the last stream.
Listening for 'error' will recieve errors from all streams inside the pipe.
``` js
es.connect( //connect streams together with `pipe`
process.openStdin(), //open stdin
es.split(), //split stream to break on newlines
es.map(function (data, callback) {//turn this async function into a stream
callback(null
, inspect(JSON.parse(data))) //render it nicely
}),
process.stdout // pipe it to stdout !
)
```
## gate (isShut=true)
If the gate is `shut`, buffer the stream.
All calls to write will return false (pause upstream),
and end will not be sent downstream.
If the gate is open, let the stream through.
Named `shut` instead of close, because close is already kinda meaningful with streams.
Gate is useful for holding off processing a stream until some resource (i.e. a database, or network connection) is ready.
``` js
var gate = es.gate()
gate.open() //allow the gate to stream
gate.close() //buffer the stream, also do not allow 'end'
```
## duplex
Takes a writable stream and a readable stream and makes them appear as a readable writable stream.
It is assumed that the two streams are connected to each other in some way.
(This is used by `connect` and `child`.)
``` js
var grep = cp.exec('grep Stream')
es.duplex(grep.stdin, grep.stdout)
```
## child (child_process)
Create a through stream from a child process ...
``` js
var cp = require('child_process')
es.child(cp.exec('grep Stream')) // a through stream
```
## pipeable (streamCreatorFunction,...)
The arguments to pipable must be functions that return
instances of Stream or async functions.
(If a function is returned, it will be turned into a Stream
with `es.map`.)
Here is the first example rewritten to use `pipeable`.
``` js
//examples/pretty_pipeable.js
var inspect = require('util').inspect
if(!module.parent)
require('event-stream').pipeable(function () {
return function (data, callback) {
try {
data = JSON.parse(data)
} catch (err) {} //pass non JSON straight through!
callback(null, inspect(data))
}
})
})
```
``` bash
curl -sS registry.npmjs.org/event-stream | node pipeable_pretty.js
## or, turn the pipe into a server!
node pipeable_pretty.js --port 4646
curl -sS registry.npmjs.org/event-stream | curl -sSNT- localhost:4646
```
## compatible modules:
* https://github.com/felixge/node-growing-file
stream changes on file that is being appended to. just like `tail -f`
* https://github.com/isaacs/sax-js
streaming xml parser
* https://github.com/mikeal/request
make http requests. request() returns a through stream!
* https://github.com/TooTallNate/node-throttle
throttle streams on a bytes per second basis (binary streams only, of course)
* https://github.com/mikeal/morestreams
buffer input until connected to a pipe.
* https://github.com/TooTallNate/node-gzip-stack
compress and decompress raw streams.
* https://github.com/Floby/node-json-streams
parse json without buffering it first
* https://github.com/floby/node-tokenizer
tokenizer
* https://github.com/floby/node-parser
general mechanisms for custom parsers
* https://github.com/dodo/node-bufferstream
buffer streams until you say (written in C)
* https://github.com/tim-smart/node-filter
`filter` pipeable string.replace
## almost compatible modules: (1+ these issues)
* https://github.com/fictorial/json-line-protocol/issues/1
line reader
* https://github.com/jahewson/node-byline/issues/1
line reader
* https://github.com/AvianFlu/ntwitter/issues/3
twitter client
* https://github.com/swdyh/node-chirpstream/issues/1
twitter client
* https://github.com/polotek/evented-twitter/issues/22
twitter client
<!--
TODO, the following methods are not implemented yet.
## sidestream (stream1,...,streamN)
Pipes the incoming stream to many writable streams.
remits the input stream.
``` js
es.sidestream( //will log the stream to a file
es.connect(
es.mapSync(function (j) {return JSON.stringify(j) + '/n'}),
fs.createWruteStream(file, {flags: 'a'})
)
```
## merge (stream1,...,streamN)
Create a readable stream that merges many streams into one.
(Not implemented yet.)
### another pipe example
SEARCH SUBDIRECTORIES FROM CWD
FILTER IF NOT A GIT REPO
MAP TO GIT STATUS --porclean + the directory
FILTER IF EMPTY STATUS
process.stdout
that will show all the repos which have unstaged changes
## TODO & applications
* buffer -- buffer items
* rate limiter
* save to database
* couch
* redis
* mongo
* file(s)
* read from database
* couch
* redis
* mongo
* file(s)
* recursive
* search filesystem
* scrape web pages (load pages, parse for links, etc)
* module dependencies
-->

3
node_modules/event-stream/test/.npmignore generated vendored Normal file
View File

@@ -0,0 +1,3 @@
node_modules
node_modules/*
npm_debug.log

11
node_modules/event-stream/test/package.json generated vendored Normal file
View File

@@ -0,0 +1,11 @@
{ "name": "event-stream_tests/"
, "version": "0.0.0"
, "description": ""
, "homepage": "http://github.com/dominictarr/event-stream_tests/"
, "repository":
{ "type": "git"
, "url": "https://github.com/dominictarr/event-stream_tests/.git" }
, "dependencies": {}
, "devDependencies": {}
, "author": "Dominic Tarr <dominic.tarr@gmail.com> (http://bit.ly/dominictarr)"
, "scripts": { "test": "meta-test test/*.js" } }

54
node_modules/event-stream/test/pipe.async.js generated vendored Normal file
View File

@@ -0,0 +1,54 @@
var es = require('event-stream')
, it = require('it-is').style('colour')
, d = require('d-utils')
function makeExamplePipe() {
return es.pipe(
es.map(function (data, callback) {
callback(null, data * 2)
}),
es.map(function (data, callback) {
d.delay(callback)(null, data)
}),
es.map(function (data, callback) {
callback(null, data + 2)
}))
}
exports['simple pipe'] = function (test) {
var pipe = makeExamplePipe()
pipe.on('data', function (data) {
it(data).equal(18)
test.done()
})
pipe.write(8)
}
exports['read array then map'] = function (test) {
var readThis = d.map(3, 6, 100, d.id) //array of multiples of 3 < 100
, first = es.readArray(readThis)
, read = []
, pipe =
es.pipe(
first,
es.map(function (data, callback) {
callback(null, {data: data})
}),
es.map(function (data, callback) {
callback(null, {data: data})
}),
es.writeArray(function (err, array) {
it(array).deepEqual(d.map(readThis, function (data) {
return {data: {data: data}}
}))
test.done()
})
)
}

88
node_modules/event-stream/test/readArray.asynct.js generated vendored Normal file
View File

@@ -0,0 +1,88 @@
var es = require('event-stream')
, it = require('it-is').style('colour')
, d = require('d-utils')
function readStream(stream, pauseAt, done) {
if(!done) done = pauseAt, pauseAt = -1
var array = []
stream.on('data', function (data) {
array.push(data)
if(!--pauseAt )
stream.pause(), done(null, array)
})
stream.on('error', done)
stream.on('end', function (data) {
done(null, array)
})
}
exports ['read an array'] = function (test) {
var readThis = d.map(3, 6, 100, d.id) //array of multiples of 3 < 100
var reader = es.readArray(readThis)
var writer = es.writeArray(function (err, array){
if(err) throw err //unpossible
it(array).deepEqual(readThis)
test.done()
})
reader.pipe(writer)
}
exports ['read an array and pause it.'] = function (test) {
var readThis = d.map(3, 6, 100, d.id) //array of multiples of 3 < 100
var reader = es.readArray(readThis)
readStream(reader, 10, function (err, data) {
if(err) throw err
it(data).deepEqual([3, 6, 9, 12, 15, 18, 21, 24, 27, 30])
readStream(reader, 10, function (err, data) {
it(data).deepEqual([33, 36, 39, 42, 45, 48, 51, 54, 57, 60])
test.done()
})
reader.resume()
})
}
exports ['reader is readable, but not writeable'] = function (test) {
var reader = es.readArray([1])
it(reader).has({
readable: true,
writable: false
})
test.done()
}
exports ['read one item per tick'] = function (test) {
var readThis = d.map(3, 6, 100, d.id) //array of multiples of 3 < 100
var drains = 0
var reader = es.readArray(readThis)
var tickMapper = es.map(function (data,callback) {
process.nextTick(function () {
callback(null, data)
})
//since tickMapper is returning false
//pipe should pause the writer until a drain occurs
return false
})
reader.pipe(tickMapper)
readStream(tickMapper, function (err, array) {
it(array).deepEqual(readThis)
it(array.length).deepEqual(readThis.length)
it(drains).equal(readThis.length)
test.done()
})
tickMapper.on('drain', function () {
drains ++
})
}

0
node_modules/event-stream/test/readme.markdown generated vendored Normal file
View File

96
node_modules/event-stream/test/simple-map.asynct.js generated vendored Normal file
View File

@@ -0,0 +1,96 @@
var es = require('event-stream')
, it = require('it-is')
function writeArray(array, stream) {
array.forEach( function (j) {
stream.write(j)
})
stream.end()
}
function readStream(stream, done) {
var array = []
stream.on('data', function (data) {
array.push(data)
})
stream.on('error', done)
stream.on('end', function (data) {
done(null, array)
})
}
exports ['simple map applied to a stream'] = function (test) {
var input = [1,2,3,7,5,3,1,9,0,2,4,6]
//create event stream from
var doubler = es.map(function (data, cb) {
cb(null, data * 2)
})
readStream(doubler, function (err, output) {
it(output).deepEqual(input.map(function (j) {
return j * 2
}))
test.done()
})
writeArray(input, doubler)
}
exports['pipe two maps together'] = function (test) {
var input = [1,2,3,7,5,3,1,9,0,2,4,6]
//create event stream from
function dd (data, cb) {
cb(null, data * 2)
}
var doubler1 = es.map(dd), doubler2 = es.map(dd)
doubler1.pipe(doubler2)
readStream(doubler2, function (err, output) {
it(output).deepEqual(input.map(function (j) {
return j * 4
}))
test.done()
})
writeArray(input, doubler1)
}
//next:
//
// test pause, resume and drian.
//
// then make a pipe joiner:
//
// plumber (evStr1, evStr2, evStr3, evStr4, evStr5)
//
// will return a single stream that write goes to the first
exports ['map will not call end until the callback'] = function (test) {
var ticker = es.map(function (data, cb) {
process.nextTick(function () {
cb(null, data * 2)
})
})
ticker.write('x')
ticker.end()
ticker.end()
ticker.end()
ticker.on('end', function () {
test.done()
})
}

34
node_modules/event-stream/test/split.asynct.js generated vendored Normal file
View File

@@ -0,0 +1,34 @@
var es = require('event-stream')
, it = require('it-is').style('colour')
, d = require('d-utils')
, join = require('path').join
, fs = require('fs')
, Stream = require('stream').Stream
exports ['pipeable'] = function (test) {
var readme = join(__dirname, 'readme.markdown')
, expected = fs.readFileSync(readme, 'utf-8').split('\n')
, cs = es.split()
, actual = []
, ended = false
var a = new Stream ()
a.write = function (l) {
actual.push(l.trim())
}
a.end = function () {
ended = true
expected.forEach(function (v,k) {
it(actual[k]).like(v)
})
test.done()
}
a.writable = true
fs.createReadStream(readme, {flags: 'r'}).pipe(cs)
cs.pipe(a)
}

31
node_modules/event-stream/test/writeArray.asynct.js generated vendored Normal file
View File

@@ -0,0 +1,31 @@
var es = require('event-stream')
, it = require('it-is').style('colour')
, d = require('d-utils')
exports ['write an array'] = function (test) {
var readThis = d.map(3, 6, 100, d.id) //array of multiples of 3 < 100
var writer = es.writeArray(function (err, array){
if(err) throw err //unpossible
it(array).deepEqual(readThis)
test.done()
})
d.each(readThis, writer.write.bind(writer))
writer.end()
}
exports ['writer is writable, but not readable'] = function (test) {
var reader = es.writeArray(function () {})
it(reader).has({
readable: false,
writable: true
})
test.done()
}