initial commit
This commit is contained in:
commit
d3fcd7f10c
3159 files changed
+349702
No files matched your search
+172
@@ -0,0 +1,172 @@
|
||||
[](http://travis-ci.org/visionmedia/mocha)
|
||||
|
||||
[](http://visionmedia.github.io/mocha)
|
||||
|
||||
Mocha is a simple, flexible, fun JavaScript test framework for node.js and the browser. For more information view the [documentation](http://visionmedia.github.io/mocha).
|
||||
|
||||
## Contributors
|
||||
|
||||
```
|
||||
|
||||
project : mocha
|
||||
repo age : 2 years, 4 months ago
|
||||
commits : 1314
|
||||
active : 372 days
|
||||
files : 141
|
||||
authors :
|
||||
582 TJ Holowaychuk 44.3%
|
||||
389 Tj Holowaychuk 29.6%
|
||||
46 Travis Jeffery 3.5%
|
||||
31 Guillermo Rauch 2.4%
|
||||
13 Attila Domokos 1.0%
|
||||
10 John Firebaugh 0.8%
|
||||
8 Jo Liss 0.6%
|
||||
7 Nathan Rajlich 0.5%
|
||||
6 Mike Pennisi 0.5%
|
||||
6 James Carr 0.5%
|
||||
6 Brendan Nee 0.5%
|
||||
5 Aaron Heckmann 0.4%
|
||||
5 Ryunosuke SATO 0.4%
|
||||
4 hokaccha 0.3%
|
||||
4 Joshua Krall 0.3%
|
||||
4 Xavier Antoviaque 0.3%
|
||||
3 Jesse Dailey 0.2%
|
||||
3 Forbes Lindesay 0.2%
|
||||
3 Sindre Sorhus 0.2%
|
||||
3 Cory Thomas 0.2%
|
||||
3 Fredrik Enestad 0.2%
|
||||
3 Ben Lindsey 0.2%
|
||||
3 Tyson Tate 0.2%
|
||||
3 Mathieu Desvé 0.2%
|
||||
3 Valentin Agachi 0.2%
|
||||
3 Wil Moore III 0.2%
|
||||
3 Merrick Christensen 0.2%
|
||||
3 eiji.ienaga 0.2%
|
||||
3 fool2fish 0.2%
|
||||
3 Nathan Bowser 0.2%
|
||||
3 Paul Miller 0.2%
|
||||
2 Juzer Ali 0.2%
|
||||
2 Pete Hawkins 0.2%
|
||||
2 Jonas Westerlund 0.2%
|
||||
2 Arian Stolwijk 0.2%
|
||||
2 Quang Van 0.2%
|
||||
2 Glen Mailer 0.2%
|
||||
2 Justin DuJardin 0.2%
|
||||
2 FARKAS Máté 0.2%
|
||||
2 Raynos 0.2%
|
||||
2 Michael Riley 0.2%
|
||||
2 Michael Schoonmaker 0.2%
|
||||
2 Domenic Denicola 0.2%
|
||||
2 Simon Gaeremynck 0.2%
|
||||
2 Konstantin Käfer 0.2%
|
||||
2 domenic 0.2%
|
||||
2 Paul Armstrong 0.2%
|
||||
2 fcrisci 0.2%
|
||||
2 Alexander Early 0.2%
|
||||
2 Shawn Krisman 0.2%
|
||||
2 Brian Beck 0.2%
|
||||
2 Nathan Alderson 0.2%
|
||||
2 David Henderson 0.2%
|
||||
2 Timo Tijhof 0.2%
|
||||
2 Ian Storm Taylor 0.2%
|
||||
2 travis jeffery 0.2%
|
||||
1 Matt Smith 0.1%
|
||||
1 Matthew Shanley 0.1%
|
||||
1 Nathan Black 0.1%
|
||||
1 Phil Sung 0.1%
|
||||
1 R56 0.1%
|
||||
1 Refael Ackermann 0.1%
|
||||
1 Richard Dingwall 0.1%
|
||||
1 Romain Prieto 0.1%
|
||||
1 Roman Neuhauser 0.1%
|
||||
1 Roman Shtylman 0.1%
|
||||
1 Russ Bradberry 0.1%
|
||||
1 Russell Munson 0.1%
|
||||
1 Rustem Mustafin 0.1%
|
||||
1 Salehen Shovon Rahman 0.1%
|
||||
1 Sasha Koss 0.1%
|
||||
1 Seiya Konno 0.1%
|
||||
1 Simon Goumaz 0.1%
|
||||
1 Standa Opichal 0.1%
|
||||
1 Stephen Mathieson 0.1%
|
||||
1 Steve Mason 0.1%
|
||||
1 Tapiwa Kelvin 0.1%
|
||||
1 Teddy Zeenny 0.1%
|
||||
1 Tim Ehat 0.1%
|
||||
1 Vadim Nikitin 0.1%
|
||||
1 Victor Costan 0.1%
|
||||
1 Will Langstroth 0.1%
|
||||
1 Yanis Wang 0.1%
|
||||
1 Yuest Wang 0.1%
|
||||
1 abrkn 0.1%
|
||||
1 airportyh 0.1%
|
||||
1 badunk 0.1%
|
||||
1 fengmk2 0.1%
|
||||
1 grasGendarme 0.1%
|
||||
1 lodr 0.1%
|
||||
1 tgautier@yahoo.com 0.1%
|
||||
1 traleig1 0.1%
|
||||
1 vlad 0.1%
|
||||
1 yuitest 0.1%
|
||||
1 Adam Crabtree 0.1%
|
||||
1 Andreas Brekken 0.1%
|
||||
1 Andreas Lind Petersen 0.1%
|
||||
1 Andrew Nesbitt 0.1%
|
||||
1 Andrey Popp 0.1%
|
||||
1 Arnaud Brousseau 0.1%
|
||||
1 Atsuya Takagi 0.1%
|
||||
1 Austin Birch 0.1%
|
||||
1 Bjørge Næss 0.1%
|
||||
1 Brian Lalor 0.1%
|
||||
1 Brian M. Carlson 0.1%
|
||||
1 Brian Moore 0.1%
|
||||
1 Bryan Donovan 0.1%
|
||||
1 Casey Foster 0.1%
|
||||
1 ChrisWren 0.1%
|
||||
1 Corey Butler 0.1%
|
||||
1 Daniel Stockman 0.1%
|
||||
1 Dave McKenna 0.1%
|
||||
1 Di Wu 0.1%
|
||||
1 Dmitry Shirokov 0.1%
|
||||
1 Fedor Indutny 0.1%
|
||||
1 Florian Margaine 0.1%
|
||||
1 Frederico Silva 0.1%
|
||||
1 Fredrik Lindin 0.1%
|
||||
1 Gareth Murphy 0.1%
|
||||
1 Gavin Mogan 0.1%
|
||||
1 Glen Huang 0.1%
|
||||
1 Greg Perkins 0.1%
|
||||
1 Harry Brundage 0.1%
|
||||
1 Herman Junge 0.1%
|
||||
1 Ian Young 0.1%
|
||||
1 Ivan 0.1%
|
||||
1 JP Bochi 0.1%
|
||||
1 Jaakko Salonen 0.1%
|
||||
1 Jakub Nešetřil 0.1%
|
||||
1 James Bowes 0.1%
|
||||
1 James Lal 0.1%
|
||||
1 Jason Barry 0.1%
|
||||
1 Javier Aranda 0.1%
|
||||
1 Jeff Kunkle 0.1%
|
||||
1 Jeremy Martin 0.1%
|
||||
1 Jimmy Cuadra 0.1%
|
||||
1 Jonathan Creamer 0.1%
|
||||
1 Jussi Virtanen 0.1%
|
||||
1 Katie Gengler 0.1%
|
||||
1 Kazuhito Hokamura 0.1%
|
||||
1 Kirill Korolyov 0.1%
|
||||
1 Koen Punt 0.1%
|
||||
1 Laszlo Bacsi 0.1%
|
||||
1 Liam Newman 0.1%
|
||||
1 László Bácsi 0.1%
|
||||
1 Maciej Małecki 0.1%
|
||||
1 Mal Graty 0.1%
|
||||
1 Marc Kuo 0.1%
|
||||
1 Matt Robenolt 0.1%
|
||||
```
|
||||
|
||||
## Links
|
||||
|
||||
- [Google Group](http://groups.google.com/group/mochajs)
|
||||
- [Wiki](https://github.com/visionmedia/mocha/wiki)
|
||||
- Mocha [Extensions and reporters](https://github.com/visionmedia/mocha/wiki)
|
||||
+467
@@ -0,0 +1,467 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var program = require('commander')
|
||||
, sprintf = require('util').format
|
||||
, path = require('path')
|
||||
, fs = require('fs')
|
||||
, glob = require('glob')
|
||||
, resolve = path.resolve
|
||||
, exists = fs.existsSync || path.existsSync
|
||||
, Mocha = require('../')
|
||||
, utils = Mocha.utils
|
||||
, interfaces = Mocha.interfaces
|
||||
, join = path.join
|
||||
, basename = path.basename
|
||||
, cwd = process.cwd()
|
||||
, mocha = new Mocha;
|
||||
|
||||
/**
|
||||
* Save timer references to avoid Sinon interfering (see GH-237).
|
||||
*/
|
||||
|
||||
var Date = global.Date
|
||||
, setTimeout = global.setTimeout
|
||||
, setInterval = global.setInterval
|
||||
, clearTimeout = global.clearTimeout
|
||||
, clearInterval = global.clearInterval;
|
||||
|
||||
/**
|
||||
* Files.
|
||||
*/
|
||||
|
||||
var files = [];
|
||||
|
||||
/**
|
||||
* Globals.
|
||||
*/
|
||||
|
||||
var globals = [];
|
||||
|
||||
/**
|
||||
* Requires.
|
||||
*/
|
||||
|
||||
var requires = [];
|
||||
|
||||
/**
|
||||
* Images.
|
||||
*/
|
||||
|
||||
var images = {
|
||||
fail: __dirname + '/../images/error.png'
|
||||
, pass: __dirname + '/../images/ok.png'
|
||||
};
|
||||
|
||||
// options
|
||||
|
||||
program
|
||||
.version(JSON.parse(fs.readFileSync(__dirname + '/../package.json', 'utf8')).version)
|
||||
.usage('[debug] [options] [files]')
|
||||
.option('-r, --require <name>', 'require the given module')
|
||||
.option('-R, --reporter <name>', 'specify the reporter to use', 'dot')
|
||||
.option('-u, --ui <name>', 'specify user-interface (bdd|tdd|exports)', 'bdd')
|
||||
.option('-g, --grep <pattern>', 'only run tests matching <pattern>')
|
||||
.option('-i, --invert', 'inverts --grep matches')
|
||||
.option('-t, --timeout <ms>', 'set test-case timeout in milliseconds [2000]')
|
||||
.option('-s, --slow <ms>', '"slow" test threshold in milliseconds [75]')
|
||||
.option('-w, --watch', 'watch files for changes')
|
||||
.option('-c, --colors', 'force enabling of colors')
|
||||
.option('-C, --no-colors', 'force disabling of colors')
|
||||
.option('-G, --growl', 'enable growl notification support')
|
||||
.option('-d, --debug', "enable node's debugger, synonym for node --debug")
|
||||
.option('-b, --bail', "bail after first test failure")
|
||||
.option('-A, --async-only', "force all tests to take a callback (async)")
|
||||
.option('-S, --sort', "sort test files")
|
||||
.option('--recursive', 'include sub directories')
|
||||
.option('--debug-brk', "enable node's debugger breaking on the first line")
|
||||
.option('--globals <names>', 'allow the given comma-delimited global [names]', list, [])
|
||||
.option('--check-leaks', 'check for global variable leaks')
|
||||
.option('--interfaces', 'display available interfaces')
|
||||
.option('--reporters', 'display available reporters')
|
||||
.option('--compilers <ext>:<module>,...', 'use the given module(s) to compile files', list, [])
|
||||
.option('--inline-diffs', 'display actual/expected differences inline within each string')
|
||||
.option('--no-exit', 'require a clean shutdown of the event loop: mocha will not call process.exit')
|
||||
|
||||
program.name = 'mocha';
|
||||
|
||||
// init command
|
||||
|
||||
program
|
||||
.command('init <path>')
|
||||
.description('initialize a client-side mocha setup at <path>')
|
||||
.action(function(path){
|
||||
var mkdir = require('mkdirp');
|
||||
mkdir.sync(path);
|
||||
var css = fs.readFileSync(join(__dirname, '..', 'mocha.css'));
|
||||
var js = fs.readFileSync(join(__dirname, '..', 'mocha.js'));
|
||||
var tmpl = fs.readFileSync(join(__dirname, '..', 'lib/template.html'));
|
||||
fs.writeFileSync(join(path, 'mocha.css'), css);
|
||||
fs.writeFileSync(join(path, 'mocha.js'), js);
|
||||
fs.writeFileSync(join(path, 'tests.js'), '');
|
||||
fs.writeFileSync(join(path, 'index.html'), tmpl);
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
// --globals
|
||||
|
||||
program.on('globals', function(val){
|
||||
globals = globals.concat(list(val));
|
||||
});
|
||||
|
||||
// --reporters
|
||||
|
||||
program.on('reporters', function(){
|
||||
console.log();
|
||||
console.log(' dot - dot matrix');
|
||||
console.log(' doc - html documentation');
|
||||
console.log(' spec - hierarchical spec list');
|
||||
console.log(' json - single json object');
|
||||
console.log(' progress - progress bar');
|
||||
console.log(' list - spec-style listing');
|
||||
console.log(' tap - test-anything-protocol');
|
||||
console.log(' landing - unicode landing strip');
|
||||
console.log(' xunit - xunit reporter');
|
||||
console.log(' html-cov - HTML test coverage');
|
||||
console.log(' json-cov - JSON test coverage');
|
||||
console.log(' min - minimal reporter (great with --watch)');
|
||||
console.log(' json-stream - newline delimited json events');
|
||||
console.log(' markdown - markdown documentation (github flavour)');
|
||||
console.log(' nyan - nyan cat!');
|
||||
console.log();
|
||||
process.exit();
|
||||
});
|
||||
|
||||
// --interfaces
|
||||
|
||||
program.on('interfaces', function(){
|
||||
console.log('');
|
||||
console.log(' bdd');
|
||||
console.log(' tdd');
|
||||
console.log(' qunit');
|
||||
console.log(' exports');
|
||||
console.log('');
|
||||
process.exit();
|
||||
});
|
||||
|
||||
// -r, --require
|
||||
|
||||
module.paths.push(cwd, join(cwd, 'node_modules'));
|
||||
|
||||
program.on('require', function(mod){
|
||||
var abs = exists(mod) || exists(mod + '.js');
|
||||
if (abs) mod = resolve(mod);
|
||||
requires.push(mod);
|
||||
});
|
||||
|
||||
// mocha.opts support
|
||||
|
||||
try {
|
||||
var opts = fs.readFileSync('test/mocha.opts', 'utf8')
|
||||
.trim()
|
||||
.split(/\s+/);
|
||||
|
||||
process.argv = process.argv
|
||||
.slice(0, 2)
|
||||
.concat(opts.concat(process.argv.slice(2)));
|
||||
} catch (err) {
|
||||
// ignore
|
||||
}
|
||||
|
||||
// parse args
|
||||
|
||||
program.parse(process.argv);
|
||||
|
||||
// infinite stack traces
|
||||
|
||||
Error.stackTraceLimit = Infinity; // TODO: config
|
||||
|
||||
// reporter
|
||||
|
||||
mocha.reporter(program.reporter);
|
||||
|
||||
// interface
|
||||
|
||||
mocha.ui(program.ui);
|
||||
|
||||
// load reporter
|
||||
|
||||
try {
|
||||
Reporter = require('../lib/reporters/' + program.reporter);
|
||||
} catch (err) {
|
||||
try {
|
||||
Reporter = require(program.reporter);
|
||||
} catch (err) {
|
||||
throw new Error('reporter "' + program.reporter + '" does not exist');
|
||||
}
|
||||
}
|
||||
|
||||
// --no-colors
|
||||
|
||||
if (!program.colors) mocha.useColors(false);
|
||||
|
||||
// --colors
|
||||
|
||||
if (~process.argv.indexOf('--colors') ||
|
||||
~process.argv.indexOf('-c')) {
|
||||
mocha.useColors(true);
|
||||
}
|
||||
|
||||
// --inline-diffs
|
||||
|
||||
if (program.inlineDiffs) mocha.useInlineDiffs(true);
|
||||
|
||||
// --slow <ms>
|
||||
|
||||
if (program.slow) mocha.suite.slow(program.slow);
|
||||
|
||||
// --timeout
|
||||
|
||||
if (program.timeout) mocha.suite.timeout(program.timeout);
|
||||
|
||||
// --bail
|
||||
|
||||
mocha.suite.bail(program.bail);
|
||||
|
||||
// --grep
|
||||
|
||||
if (program.grep) mocha.grep(new RegExp(program.grep));
|
||||
|
||||
// --invert
|
||||
|
||||
if (program.invert) mocha.invert();
|
||||
|
||||
// --check-leaks
|
||||
|
||||
if (program.checkLeaks) mocha.checkLeaks();
|
||||
|
||||
// --growl
|
||||
|
||||
if (program.growl) mocha.growl();
|
||||
|
||||
// --async-only
|
||||
|
||||
if (program.asyncOnly) mocha.asyncOnly();
|
||||
|
||||
// --globals
|
||||
|
||||
mocha.globals(globals);
|
||||
|
||||
// custom compiler support
|
||||
|
||||
var extensions = ['js'];
|
||||
program.compilers.forEach(function(c) {
|
||||
var compiler = c.split(':')
|
||||
, ext = compiler[0]
|
||||
, mod = compiler[1];
|
||||
|
||||
if (mod[0] == '.') mod = join(process.cwd(), mod);
|
||||
require(mod);
|
||||
extensions.push(ext);
|
||||
});
|
||||
|
||||
var re = new RegExp('\\.(' + extensions.join('|') + ')$');
|
||||
|
||||
// requires
|
||||
|
||||
requires.forEach(function(mod) {
|
||||
require(mod);
|
||||
});
|
||||
|
||||
// files
|
||||
|
||||
var files = []
|
||||
, args = program.args;
|
||||
|
||||
// default files to test/*.{js,coffee}
|
||||
|
||||
if (!args.length) args.push('test');
|
||||
|
||||
args.forEach(function(arg){
|
||||
files = files.concat(lookupFiles(arg, program.recursive));
|
||||
});
|
||||
|
||||
// resolve
|
||||
|
||||
files = files.map(function(path){
|
||||
return resolve(path);
|
||||
});
|
||||
|
||||
if (program.sort) {
|
||||
files.sort();
|
||||
}
|
||||
|
||||
// --watch
|
||||
|
||||
var runner;
|
||||
if (program.watch) {
|
||||
console.log();
|
||||
hideCursor();
|
||||
process.on('SIGINT', function(){
|
||||
showCursor();
|
||||
console.log('\n');
|
||||
process.exit();
|
||||
});
|
||||
|
||||
var watchFiles = utils.files(cwd);
|
||||
var runAgain = false;
|
||||
|
||||
function loadAndRun() {
|
||||
try {
|
||||
mocha.files = files;
|
||||
runAgain = false;
|
||||
runner = mocha.run(function(){
|
||||
runner = null;
|
||||
if (runAgain) {
|
||||
rerun();
|
||||
}
|
||||
});
|
||||
} catch(e) {
|
||||
console.log(e.stack);
|
||||
}
|
||||
}
|
||||
|
||||
function purge() {
|
||||
watchFiles.forEach(function(file){
|
||||
delete require.cache[file];
|
||||
});
|
||||
}
|
||||
|
||||
loadAndRun();
|
||||
|
||||
function rerun() {
|
||||
purge();
|
||||
stop()
|
||||
mocha.suite = mocha.suite.clone();
|
||||
mocha.suite.ctx = new Mocha.Context;
|
||||
mocha.ui(program.ui);
|
||||
loadAndRun();
|
||||
}
|
||||
|
||||
utils.watch(watchFiles, function(){
|
||||
runAgain = true;
|
||||
if (runner) {
|
||||
runner.abort();
|
||||
} else {
|
||||
rerun();
|
||||
}
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// load
|
||||
|
||||
mocha.files = files;
|
||||
runner = mocha.run(program.exit ? process.exit : exitLater);
|
||||
|
||||
function exitLater(code) {
|
||||
process.on('exit', function() { process.exit(code) })
|
||||
}
|
||||
|
||||
process.on('SIGINT', function() { runner.abort(); })
|
||||
|
||||
// enable growl notifications
|
||||
|
||||
function growl(runner, reporter) {
|
||||
var notify = require('growl');
|
||||
|
||||
runner.on('end', function(){
|
||||
var stats = reporter.stats;
|
||||
if (stats.failures) {
|
||||
var msg = stats.failures + ' of ' + runner.total + ' tests failed';
|
||||
notify(msg, { name: 'mocha', title: 'Failed', image: images.fail });
|
||||
} else {
|
||||
notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', {
|
||||
name: 'mocha'
|
||||
, title: 'Passed'
|
||||
, image: images.pass
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse list.
|
||||
*/
|
||||
|
||||
function list(str) {
|
||||
return str.split(/ *, */);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hide the cursor.
|
||||
*/
|
||||
|
||||
function hideCursor(){
|
||||
process.stdout.write('\u001b[?25l');
|
||||
};
|
||||
|
||||
/**
|
||||
* Show the cursor.
|
||||
*/
|
||||
|
||||
function showCursor(){
|
||||
process.stdout.write('\u001b[?25h');
|
||||
};
|
||||
|
||||
/**
|
||||
* Stop play()ing.
|
||||
*/
|
||||
|
||||
function stop() {
|
||||
process.stdout.write('\u001b[2K');
|
||||
clearInterval(play.timer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lookup file names at the given `path`.
|
||||
*/
|
||||
|
||||
function lookupFiles(path, recursive) {
|
||||
var files = [];
|
||||
|
||||
if (!exists(path)) {
|
||||
if (exists(path + '.js')) {
|
||||
path += '.js'
|
||||
} else {
|
||||
files = glob.sync(path);
|
||||
if (!files.length) throw new Error("cannot resolve path (or pattern) '" + path + "'");
|
||||
return files;
|
||||
}
|
||||
}
|
||||
|
||||
var stat = fs.statSync(path);
|
||||
if (stat.isFile()) return path;
|
||||
|
||||
fs.readdirSync(path).forEach(function(file){
|
||||
file = join(path, file);
|
||||
var stat = fs.statSync(file);
|
||||
if (stat.isDirectory()) {
|
||||
if (recursive) files = files.concat(lookupFiles(file, recursive));
|
||||
return
|
||||
}
|
||||
if (!stat.isFile() || !re.test(file) || basename(file)[0] == '.') return;
|
||||
files.push(file);
|
||||
});
|
||||
|
||||
return files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Play the given array of strings.
|
||||
*/
|
||||
|
||||
function play(arr, interval) {
|
||||
var len = arr.length
|
||||
, interval = interval || 100
|
||||
, i = 0;
|
||||
|
||||
play.timer = setInterval(function(){
|
||||
var str = arr[i++ % len];
|
||||
process.stdout.write('\u001b[0G' + str);
|
||||
}, interval);
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* This tiny wrapper file checks for known node flags and appends them
|
||||
* when found, before invoking the "real" _mocha(1) executable.
|
||||
*/
|
||||
|
||||
var spawn = require('child_process').spawn
|
||||
, args = [ __dirname + '/_mocha' ];
|
||||
|
||||
process.argv.slice(2).forEach(function(arg){
|
||||
var flag = arg.split('=')[0];
|
||||
|
||||
switch (flag) {
|
||||
case '-d':
|
||||
args.unshift('--debug');
|
||||
break;
|
||||
case 'debug':
|
||||
case '--debug':
|
||||
case '--debug-brk':
|
||||
args.unshift(arg);
|
||||
break;
|
||||
case '-gc':
|
||||
case '--expose-gc':
|
||||
args.unshift('--expose-gc');
|
||||
break;
|
||||
case '--gc-global':
|
||||
case '--harmony':
|
||||
case '--harmony-proxies':
|
||||
case '--harmony-collections':
|
||||
case '--harmony-generators':
|
||||
case '--prof':
|
||||
args.unshift(arg);
|
||||
break;
|
||||
default:
|
||||
if (0 == arg.indexOf('--trace')) args.unshift(arg);
|
||||
else args.push(arg);
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
var proc = spawn(process.argv[0], args, { customFds: [0,1,2] });
|
||||
proc.on('exit', function (code, signal) {
|
||||
process.on('exit', function(){
|
||||
if (signal) {
|
||||
process.kill(process.pid, signal);
|
||||
} else {
|
||||
process.exit(code);
|
||||
}
|
||||
});
|
||||
});
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 412 B |
BIN
Binary file not shown.
|
After Width: | Height: | Size: 388 B |
+4
@@ -0,0 +1,4 @@
|
||||
|
||||
module.exports = process.env.COV
|
||||
? require('./lib-cov/mocha')
|
||||
: require('./lib/mocha');
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
|
||||
module.exports = function(type){
|
||||
return function(){
|
||||
}
|
||||
};
|
||||
+354
@@ -0,0 +1,354 @@
|
||||
/* See LICENSE file for terms of use */
|
||||
|
||||
/*
|
||||
* Text diff implementation.
|
||||
*
|
||||
* This library supports the following APIS:
|
||||
* JsDiff.diffChars: Character by character diff
|
||||
* JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
|
||||
* JsDiff.diffLines: Line based diff
|
||||
*
|
||||
* JsDiff.diffCss: Diff targeted at CSS content
|
||||
*
|
||||
* These methods are based on the implementation proposed in
|
||||
* "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
|
||||
* http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
|
||||
*/
|
||||
var JsDiff = (function() {
|
||||
/*jshint maxparams: 5*/
|
||||
function clonePath(path) {
|
||||
return { newPos: path.newPos, components: path.components.slice(0) };
|
||||
}
|
||||
function removeEmpty(array) {
|
||||
var ret = [];
|
||||
for (var i = 0; i < array.length; i++) {
|
||||
if (array[i]) {
|
||||
ret.push(array[i]);
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
function escapeHTML(s) {
|
||||
var n = s;
|
||||
n = n.replace(/&/g, '&');
|
||||
n = n.replace(/</g, '<');
|
||||
n = n.replace(/>/g, '>');
|
||||
n = n.replace(/"/g, '"');
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
var Diff = function(ignoreWhitespace) {
|
||||
this.ignoreWhitespace = ignoreWhitespace;
|
||||
};
|
||||
Diff.prototype = {
|
||||
diff: function(oldString, newString) {
|
||||
// Handle the identity case (this is due to unrolling editLength == 0
|
||||
if (newString === oldString) {
|
||||
return [{ value: newString }];
|
||||
}
|
||||
if (!newString) {
|
||||
return [{ value: oldString, removed: true }];
|
||||
}
|
||||
if (!oldString) {
|
||||
return [{ value: newString, added: true }];
|
||||
}
|
||||
|
||||
newString = this.tokenize(newString);
|
||||
oldString = this.tokenize(oldString);
|
||||
|
||||
var newLen = newString.length, oldLen = oldString.length;
|
||||
var maxEditLength = newLen + oldLen;
|
||||
var bestPath = [{ newPos: -1, components: [] }];
|
||||
|
||||
// Seed editLength = 0
|
||||
var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
|
||||
if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) {
|
||||
return bestPath[0].components;
|
||||
}
|
||||
|
||||
for (var editLength = 1; editLength <= maxEditLength; editLength++) {
|
||||
for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) {
|
||||
var basePath;
|
||||
var addPath = bestPath[diagonalPath-1],
|
||||
removePath = bestPath[diagonalPath+1];
|
||||
oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
|
||||
if (addPath) {
|
||||
// No one else is going to attempt to use this value, clear it
|
||||
bestPath[diagonalPath-1] = undefined;
|
||||
}
|
||||
|
||||
var canAdd = addPath && addPath.newPos+1 < newLen;
|
||||
var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
|
||||
if (!canAdd && !canRemove) {
|
||||
bestPath[diagonalPath] = undefined;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Select the diagonal that we want to branch from. We select the prior
|
||||
// path whose position in the new string is the farthest from the origin
|
||||
// and does not pass the bounds of the diff graph
|
||||
if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
|
||||
basePath = clonePath(removePath);
|
||||
this.pushComponent(basePath.components, oldString[oldPos], undefined, true);
|
||||
} else {
|
||||
basePath = clonePath(addPath);
|
||||
basePath.newPos++;
|
||||
this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined);
|
||||
}
|
||||
|
||||
var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath);
|
||||
|
||||
if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) {
|
||||
return basePath.components;
|
||||
} else {
|
||||
bestPath[diagonalPath] = basePath;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
pushComponent: function(components, value, added, removed) {
|
||||
var last = components[components.length-1];
|
||||
if (last && last.added === added && last.removed === removed) {
|
||||
// We need to clone here as the component clone operation is just
|
||||
// as shallow array clone
|
||||
components[components.length-1] =
|
||||
{value: this.join(last.value, value), added: added, removed: removed };
|
||||
} else {
|
||||
components.push({value: value, added: added, removed: removed });
|
||||
}
|
||||
},
|
||||
extractCommon: function(basePath, newString, oldString, diagonalPath) {
|
||||
var newLen = newString.length,
|
||||
oldLen = oldString.length,
|
||||
newPos = basePath.newPos,
|
||||
oldPos = newPos - diagonalPath;
|
||||
while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) {
|
||||
newPos++;
|
||||
oldPos++;
|
||||
|
||||
this.pushComponent(basePath.components, newString[newPos], undefined, undefined);
|
||||
}
|
||||
basePath.newPos = newPos;
|
||||
return oldPos;
|
||||
},
|
||||
|
||||
equals: function(left, right) {
|
||||
var reWhitespace = /\S/;
|
||||
if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) {
|
||||
return true;
|
||||
} else {
|
||||
return left === right;
|
||||
}
|
||||
},
|
||||
join: function(left, right) {
|
||||
return left + right;
|
||||
},
|
||||
tokenize: function(value) {
|
||||
return value;
|
||||
}
|
||||
};
|
||||
|
||||
var CharDiff = new Diff();
|
||||
|
||||
var WordDiff = new Diff(true);
|
||||
var WordWithSpaceDiff = new Diff();
|
||||
WordDiff.tokenize = WordWithSpaceDiff.tokenize = function(value) {
|
||||
return removeEmpty(value.split(/(\s+|\b)/));
|
||||
};
|
||||
|
||||
var CssDiff = new Diff(true);
|
||||
CssDiff.tokenize = function(value) {
|
||||
return removeEmpty(value.split(/([{}:;,]|\s+)/));
|
||||
};
|
||||
|
||||
var LineDiff = new Diff();
|
||||
LineDiff.tokenize = function(value) {
|
||||
return value.split(/^/m);
|
||||
};
|
||||
|
||||
return {
|
||||
Diff: Diff,
|
||||
|
||||
diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); },
|
||||
diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); },
|
||||
diffWordsWithSpace: function(oldStr, newStr) { return WordWithSpaceDiff.diff(oldStr, newStr); },
|
||||
diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); },
|
||||
|
||||
diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); },
|
||||
|
||||
createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) {
|
||||
var ret = [];
|
||||
|
||||
ret.push('Index: ' + fileName);
|
||||
ret.push('===================================================================');
|
||||
ret.push('--- ' + fileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader));
|
||||
ret.push('+++ ' + fileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader));
|
||||
|
||||
var diff = LineDiff.diff(oldStr, newStr);
|
||||
if (!diff[diff.length-1].value) {
|
||||
diff.pop(); // Remove trailing newline add
|
||||
}
|
||||
diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier
|
||||
|
||||
function contextLines(lines) {
|
||||
return lines.map(function(entry) { return ' ' + entry; });
|
||||
}
|
||||
function eofNL(curRange, i, current) {
|
||||
var last = diff[diff.length-2],
|
||||
isLast = i === diff.length-2,
|
||||
isLastOfType = i === diff.length-3 && (current.added !== last.added || current.removed !== last.removed);
|
||||
|
||||
// Figure out if this is the last line for the given file and missing NL
|
||||
if (!/\n$/.test(current.value) && (isLast || isLastOfType)) {
|
||||
curRange.push('\\ No newline at end of file');
|
||||
}
|
||||
}
|
||||
|
||||
var oldRangeStart = 0, newRangeStart = 0, curRange = [],
|
||||
oldLine = 1, newLine = 1;
|
||||
for (var i = 0; i < diff.length; i++) {
|
||||
var current = diff[i],
|
||||
lines = current.lines || current.value.replace(/\n$/, '').split('\n');
|
||||
current.lines = lines;
|
||||
|
||||
if (current.added || current.removed) {
|
||||
if (!oldRangeStart) {
|
||||
var prev = diff[i-1];
|
||||
oldRangeStart = oldLine;
|
||||
newRangeStart = newLine;
|
||||
|
||||
if (prev) {
|
||||
curRange = contextLines(prev.lines.slice(-4));
|
||||
oldRangeStart -= curRange.length;
|
||||
newRangeStart -= curRange.length;
|
||||
}
|
||||
}
|
||||
curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?'+':'-') + entry; }));
|
||||
eofNL(curRange, i, current);
|
||||
|
||||
if (current.added) {
|
||||
newLine += lines.length;
|
||||
} else {
|
||||
oldLine += lines.length;
|
||||
}
|
||||
} else {
|
||||
if (oldRangeStart) {
|
||||
// Close out any changes that have been output (or join overlapping)
|
||||
if (lines.length <= 8 && i < diff.length-2) {
|
||||
// Overlapping
|
||||
curRange.push.apply(curRange, contextLines(lines));
|
||||
} else {
|
||||
// end the range and output
|
||||
var contextSize = Math.min(lines.length, 4);
|
||||
ret.push(
|
||||
'@@ -' + oldRangeStart + ',' + (oldLine-oldRangeStart+contextSize)
|
||||
+ ' +' + newRangeStart + ',' + (newLine-newRangeStart+contextSize)
|
||||
+ ' @@');
|
||||
ret.push.apply(ret, curRange);
|
||||
ret.push.apply(ret, contextLines(lines.slice(0, contextSize)));
|
||||
if (lines.length <= 4) {
|
||||
eofNL(ret, i, current);
|
||||
}
|
||||
|
||||
oldRangeStart = 0; newRangeStart = 0; curRange = [];
|
||||
}
|
||||
}
|
||||
oldLine += lines.length;
|
||||
newLine += lines.length;
|
||||
}
|
||||
}
|
||||
|
||||
return ret.join('\n') + '\n';
|
||||
},
|
||||
|
||||
applyPatch: function(oldStr, uniDiff) {
|
||||
var diffstr = uniDiff.split('\n');
|
||||
var diff = [];
|
||||
var remEOFNL = false,
|
||||
addEOFNL = false;
|
||||
|
||||
for (var i = (diffstr[0][0]==='I'?4:0); i < diffstr.length; i++) {
|
||||
if(diffstr[i][0] === '@') {
|
||||
var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/);
|
||||
diff.unshift({
|
||||
start:meh[3],
|
||||
oldlength:meh[2],
|
||||
oldlines:[],
|
||||
newlength:meh[4],
|
||||
newlines:[]
|
||||
});
|
||||
} else if(diffstr[i][0] === '+') {
|
||||
diff[0].newlines.push(diffstr[i].substr(1));
|
||||
} else if(diffstr[i][0] === '-') {
|
||||
diff[0].oldlines.push(diffstr[i].substr(1));
|
||||
} else if(diffstr[i][0] === ' ') {
|
||||
diff[0].newlines.push(diffstr[i].substr(1));
|
||||
diff[0].oldlines.push(diffstr[i].substr(1));
|
||||
} else if(diffstr[i][0] === '\\') {
|
||||
if (diffstr[i-1][0] === '+') {
|
||||
remEOFNL = true;
|
||||
} else if(diffstr[i-1][0] === '-') {
|
||||
addEOFNL = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var str = oldStr.split('\n');
|
||||
for (var i = diff.length - 1; i >= 0; i--) {
|
||||
var d = diff[i];
|
||||
for (var j = 0; j < d.oldlength; j++) {
|
||||
if(str[d.start-1+j] !== d.oldlines[j]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines));
|
||||
}
|
||||
|
||||
if (remEOFNL) {
|
||||
while (!str[str.length-1]) {
|
||||
str.pop();
|
||||
}
|
||||
} else if (addEOFNL) {
|
||||
str.push('');
|
||||
}
|
||||
return str.join('\n');
|
||||
},
|
||||
|
||||
convertChangesToXML: function(changes){
|
||||
var ret = [];
|
||||
for ( var i = 0; i < changes.length; i++) {
|
||||
var change = changes[i];
|
||||
if (change.added) {
|
||||
ret.push('<ins>');
|
||||
} else if (change.removed) {
|
||||
ret.push('<del>');
|
||||
}
|
||||
|
||||
ret.push(escapeHTML(change.value));
|
||||
|
||||
if (change.added) {
|
||||
ret.push('</ins>');
|
||||
} else if (change.removed) {
|
||||
ret.push('</del>');
|
||||
}
|
||||
}
|
||||
return ret.join('');
|
||||
},
|
||||
|
||||
// See: http://code.google.com/p/google-diff-match-patch/wiki/API
|
||||
convertChangesToDMP: function(changes){
|
||||
var ret = [], change;
|
||||
for ( var i = 0; i < changes.length; i++) {
|
||||
change = changes[i];
|
||||
ret.push([(change.added ? 1 : change.removed ? -1 : 0), change.value]);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
};
|
||||
})();
|
||||
|
||||
if (typeof module !== 'undefined') {
|
||||
module.exports = JsDiff;
|
||||
}
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
exports.EventEmitter = EventEmitter;
|
||||
|
||||
/**
|
||||
* Check if `obj` is an array.
|
||||
*/
|
||||
|
||||
function isArray(obj) {
|
||||
return '[object Array]' == {}.toString.call(obj);
|
||||
}
|
||||
|
||||
/**
|
||||
* Event emitter constructor.
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function EventEmitter(){};
|
||||
|
||||
/**
|
||||
* Adds a listener.
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
|
||||
EventEmitter.prototype.on = function (name, fn) {
|
||||
if (!this.$events) {
|
||||
this.$events = {};
|
||||
}
|
||||
|
||||
if (!this.$events[name]) {
|
||||
this.$events[name] = fn;
|
||||
} else if (isArray(this.$events[name])) {
|
||||
this.$events[name].push(fn);
|
||||
} else {
|
||||
this.$events[name] = [this.$events[name], fn];
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
EventEmitter.prototype.addListener = EventEmitter.prototype.on;
|
||||
|
||||
/**
|
||||
* Adds a volatile listener.
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
|
||||
EventEmitter.prototype.once = function (name, fn) {
|
||||
var self = this;
|
||||
|
||||
function on () {
|
||||
self.removeListener(name, on);
|
||||
fn.apply(this, arguments);
|
||||
};
|
||||
|
||||
on.listener = fn;
|
||||
this.on(name, on);
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Removes a listener.
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
|
||||
EventEmitter.prototype.removeListener = function (name, fn) {
|
||||
if (this.$events && this.$events[name]) {
|
||||
var list = this.$events[name];
|
||||
|
||||
if (isArray(list)) {
|
||||
var pos = -1;
|
||||
|
||||
for (var i = 0, l = list.length; i < l; i++) {
|
||||
if (list[i] === fn || (list[i].listener && list[i].listener === fn)) {
|
||||
pos = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (pos < 0) {
|
||||
return this;
|
||||
}
|
||||
|
||||
list.splice(pos, 1);
|
||||
|
||||
if (!list.length) {
|
||||
delete this.$events[name];
|
||||
}
|
||||
} else if (list === fn || (list.listener && list.listener === fn)) {
|
||||
delete this.$events[name];
|
||||
}
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Removes all listeners for an event.
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
|
||||
EventEmitter.prototype.removeAllListeners = function (name) {
|
||||
if (name === undefined) {
|
||||
this.$events = {};
|
||||
return this;
|
||||
}
|
||||
|
||||
if (this.$events && this.$events[name]) {
|
||||
this.$events[name] = null;
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets all listeners for a certain event.
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
|
||||
EventEmitter.prototype.listeners = function (name) {
|
||||
if (!this.$events) {
|
||||
this.$events = {};
|
||||
}
|
||||
|
||||
if (!this.$events[name]) {
|
||||
this.$events[name] = [];
|
||||
}
|
||||
|
||||
if (!isArray(this.$events[name])) {
|
||||
this.$events[name] = [this.$events[name]];
|
||||
}
|
||||
|
||||
return this.$events[name];
|
||||
};
|
||||
|
||||
/**
|
||||
* Emits an event.
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
|
||||
EventEmitter.prototype.emit = function (name) {
|
||||
if (!this.$events) {
|
||||
return false;
|
||||
}
|
||||
|
||||
var handler = this.$events[name];
|
||||
|
||||
if (!handler) {
|
||||
return false;
|
||||
}
|
||||
|
||||
var args = [].slice.call(arguments, 1);
|
||||
|
||||
if ('function' == typeof handler) {
|
||||
handler.apply(this, args);
|
||||
} else if (isArray(handler)) {
|
||||
var listeners = handler.slice();
|
||||
|
||||
for (var i = 0, l = listeners.length; i < l; i++) {
|
||||
listeners[i].apply(this, args);
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
Whitespace-only changes.
Whitespace-only changes.
+125
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* Expose `Progress`.
|
||||
*/
|
||||
|
||||
module.exports = Progress;
|
||||
|
||||
/**
|
||||
* Initialize a new `Progress` indicator.
|
||||
*/
|
||||
|
||||
function Progress() {
|
||||
this.percent = 0;
|
||||
this.size(0);
|
||||
this.fontSize(11);
|
||||
this.font('helvetica, arial, sans-serif');
|
||||
}
|
||||
|
||||
/**
|
||||
* Set progress size to `n`.
|
||||
*
|
||||
* @param {Number} n
|
||||
* @return {Progress} for chaining
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Progress.prototype.size = function(n){
|
||||
this._size = n;
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Set text to `str`.
|
||||
*
|
||||
* @param {String} str
|
||||
* @return {Progress} for chaining
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Progress.prototype.text = function(str){
|
||||
this._text = str;
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Set font size to `n`.
|
||||
*
|
||||
* @param {Number} n
|
||||
* @return {Progress} for chaining
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Progress.prototype.fontSize = function(n){
|
||||
this._fontSize = n;
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Set font `family`.
|
||||
*
|
||||
* @param {String} family
|
||||
* @return {Progress} for chaining
|
||||
*/
|
||||
|
||||
Progress.prototype.font = function(family){
|
||||
this._font = family;
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Update percentage to `n`.
|
||||
*
|
||||
* @param {Number} n
|
||||
* @return {Progress} for chaining
|
||||
*/
|
||||
|
||||
Progress.prototype.update = function(n){
|
||||
this.percent = n;
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Draw on `ctx`.
|
||||
*
|
||||
* @param {CanvasRenderingContext2d} ctx
|
||||
* @return {Progress} for chaining
|
||||
*/
|
||||
|
||||
Progress.prototype.draw = function(ctx){
|
||||
try {
|
||||
var percent = Math.min(this.percent, 100)
|
||||
, size = this._size
|
||||
, half = size / 2
|
||||
, x = half
|
||||
, y = half
|
||||
, rad = half - 1
|
||||
, fontSize = this._fontSize;
|
||||
|
||||
ctx.font = fontSize + 'px ' + this._font;
|
||||
|
||||
var angle = Math.PI * 2 * (percent / 100);
|
||||
ctx.clearRect(0, 0, size, size);
|
||||
|
||||
// outer circle
|
||||
ctx.strokeStyle = '#9f9f9f';
|
||||
ctx.beginPath();
|
||||
ctx.arc(x, y, rad, 0, angle, false);
|
||||
ctx.stroke();
|
||||
|
||||
// inner circle
|
||||
ctx.strokeStyle = '#eee';
|
||||
ctx.beginPath();
|
||||
ctx.arc(x, y, rad - 1, 0, angle, true);
|
||||
ctx.stroke();
|
||||
|
||||
// text
|
||||
var text = this._text || (percent | 0) + '%'
|
||||
, w = ctx.measureText(text).width;
|
||||
|
||||
ctx.fillText(
|
||||
text
|
||||
, x - w / 2 + 1
|
||||
, y + fontSize / 2 - 1);
|
||||
} catch (ex) {} //don't fail if we can't render progress
|
||||
return this;
|
||||
};
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
|
||||
exports.isatty = function(){
|
||||
return true;
|
||||
};
|
||||
|
||||
exports.getWindowSize = function(){
|
||||
if ('innerHeight' in global) {
|
||||
return [global.innerHeight, global.innerWidth];
|
||||
} else {
|
||||
// In a Web Worker, the DOM Window is not available.
|
||||
return [640, 480];
|
||||
}
|
||||
};
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
|
||||
/**
|
||||
* Expose `Context`.
|
||||
*/
|
||||
|
||||
module.exports = Context;
|
||||
|
||||
/**
|
||||
* Initialize a new `Context`.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function Context(){}
|
||||
|
||||
/**
|
||||
* Set or get the context `Runnable` to `runnable`.
|
||||
*
|
||||
* @param {Runnable} runnable
|
||||
* @return {Context}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Context.prototype.runnable = function(runnable){
|
||||
if (0 == arguments.length) return this._runnable;
|
||||
this.test = this._runnable = runnable;
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Set test timeout `ms`.
|
||||
*
|
||||
* @param {Number} ms
|
||||
* @return {Context} self
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Context.prototype.timeout = function(ms){
|
||||
this.runnable().timeout(ms);
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Set test slowness threshold `ms`.
|
||||
*
|
||||
* @param {Number} ms
|
||||
* @return {Context} self
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Context.prototype.slow = function(ms){
|
||||
this.runnable().slow(ms);
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Inspect the context void of `._runnable`.
|
||||
*
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Context.prototype.inspect = function(){
|
||||
return JSON.stringify(this, function(key, val){
|
||||
if ('_runnable' == key) return;
|
||||
if ('test' == key) return;
|
||||
return val;
|
||||
}, 2);
|
||||
};
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var Runnable = require('./runnable');
|
||||
|
||||
/**
|
||||
* Expose `Hook`.
|
||||
*/
|
||||
|
||||
module.exports = Hook;
|
||||
|
||||
/**
|
||||
* Initialize a new `Hook` with the given `title` and callback `fn`.
|
||||
*
|
||||
* @param {String} title
|
||||
* @param {Function} fn
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function Hook(title, fn) {
|
||||
Runnable.call(this, title, fn);
|
||||
this.type = 'hook';
|
||||
}
|
||||
|
||||
/**
|
||||
* Inherit from `Runnable.prototype`.
|
||||
*/
|
||||
|
||||
Hook.prototype.__proto__ = Runnable.prototype;
|
||||
|
||||
/**
|
||||
* Get or set the test `err`.
|
||||
*
|
||||
* @param {Error} err
|
||||
* @return {Error}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Hook.prototype.error = function(err){
|
||||
if (0 == arguments.length) {
|
||||
var err = this._error;
|
||||
this._error = null;
|
||||
return err;
|
||||
}
|
||||
|
||||
this._error = err;
|
||||
};
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var Suite = require('../suite')
|
||||
, Test = require('../test')
|
||||
, utils = require('../utils');
|
||||
|
||||
/**
|
||||
* BDD-style interface:
|
||||
*
|
||||
* describe('Array', function(){
|
||||
* describe('#indexOf()', function(){
|
||||
* it('should return -1 when not present', function(){
|
||||
*
|
||||
* });
|
||||
*
|
||||
* it('should return the index when present', function(){
|
||||
*
|
||||
* });
|
||||
* });
|
||||
* });
|
||||
*
|
||||
*/
|
||||
|
||||
module.exports = function(suite){
|
||||
var suites = [suite];
|
||||
|
||||
suite.on('pre-require', function(context, file, mocha){
|
||||
|
||||
/**
|
||||
* Execute before running tests.
|
||||
*/
|
||||
|
||||
context.before = function(fn){
|
||||
suites[0].beforeAll(fn);
|
||||
};
|
||||
|
||||
/**
|
||||
* Execute after running tests.
|
||||
*/
|
||||
|
||||
context.after = function(fn){
|
||||
suites[0].afterAll(fn);
|
||||
};
|
||||
|
||||
/**
|
||||
* Execute before each test case.
|
||||
*/
|
||||
|
||||
context.beforeEach = function(fn){
|
||||
suites[0].beforeEach(fn);
|
||||
};
|
||||
|
||||
/**
|
||||
* Execute after each test case.
|
||||
*/
|
||||
|
||||
context.afterEach = function(fn){
|
||||
suites[0].afterEach(fn);
|
||||
};
|
||||
|
||||
/**
|
||||
* Describe a "suite" with the given `title`
|
||||
* and callback `fn` containing nested suites
|
||||
* and/or tests.
|
||||
*/
|
||||
|
||||
context.describe = context.context = function(title, fn){
|
||||
var suite = Suite.create(suites[0], title);
|
||||
suites.unshift(suite);
|
||||
fn.call(suite);
|
||||
suites.shift();
|
||||
return suite;
|
||||
};
|
||||
|
||||
/**
|
||||
* Pending describe.
|
||||
*/
|
||||
|
||||
context.xdescribe =
|
||||
context.xcontext =
|
||||
context.describe.skip = function(title, fn){
|
||||
var suite = Suite.create(suites[0], title);
|
||||
suite.pending = true;
|
||||
suites.unshift(suite);
|
||||
fn.call(suite);
|
||||
suites.shift();
|
||||
};
|
||||
|
||||
/**
|
||||
* Exclusive suite.
|
||||
*/
|
||||
|
||||
context.describe.only = function(title, fn){
|
||||
var suite = context.describe(title, fn);
|
||||
mocha.grep(suite.fullTitle());
|
||||
return suite;
|
||||
};
|
||||
|
||||
/**
|
||||
* Describe a specification or test-case
|
||||
* with the given `title` and callback `fn`
|
||||
* acting as a thunk.
|
||||
*/
|
||||
|
||||
context.it = context.specify = function(title, fn){
|
||||
var suite = suites[0];
|
||||
if (suite.pending) var fn = null;
|
||||
var test = new Test(title, fn);
|
||||
suite.addTest(test);
|
||||
return test;
|
||||
};
|
||||
|
||||
/**
|
||||
* Exclusive test-case.
|
||||
*/
|
||||
|
||||
context.it.only = function(title, fn){
|
||||
var test = context.it(title, fn);
|
||||
var reString = '^' + utils.escapeRegexp(test.fullTitle()) + '$';
|
||||
mocha.grep(new RegExp(reString));
|
||||
return test;
|
||||
};
|
||||
|
||||
/**
|
||||
* Pending test case.
|
||||
*/
|
||||
|
||||
context.xit =
|
||||
context.xspecify =
|
||||
context.it.skip = function(title){
|
||||
context.it(title);
|
||||
};
|
||||
});
|
||||
};
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var Suite = require('../suite')
|
||||
, Test = require('../test');
|
||||
|
||||
/**
|
||||
* TDD-style interface:
|
||||
*
|
||||
* exports.Array = {
|
||||
* '#indexOf()': {
|
||||
* 'should return -1 when the value is not present': function(){
|
||||
*
|
||||
* },
|
||||
*
|
||||
* 'should return the correct index when the value is present': function(){
|
||||
*
|
||||
* }
|
||||
* }
|
||||
* };
|
||||
*
|
||||
*/
|
||||
|
||||
module.exports = function(suite){
|
||||
var suites = [suite];
|
||||
|
||||
suite.on('require', visit);
|
||||
|
||||
function visit(obj) {
|
||||
var suite;
|
||||
for (var key in obj) {
|
||||
if ('function' == typeof obj[key]) {
|
||||
var fn = obj[key];
|
||||
switch (key) {
|
||||
case 'before':
|
||||
suites[0].beforeAll(fn);
|
||||
break;
|
||||
case 'after':
|
||||
suites[0].afterAll(fn);
|
||||
break;
|
||||
case 'beforeEach':
|
||||
suites[0].beforeEach(fn);
|
||||
break;
|
||||
case 'afterEach':
|
||||
suites[0].afterEach(fn);
|
||||
break;
|
||||
default:
|
||||
suites[0].addTest(new Test(key, fn));
|
||||
}
|
||||
} else {
|
||||
var suite = Suite.create(suites[0], key);
|
||||
suites.unshift(suite);
|
||||
visit(obj[key]);
|
||||
suites.shift();
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
|
||||
exports.bdd = require('./bdd');
|
||||
exports.tdd = require('./tdd');
|
||||
exports.qunit = require('./qunit');
|
||||
exports.exports = require('./exports');
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var Suite = require('../suite')
|
||||
, Test = require('../test')
|
||||
, utils = require('../utils');
|
||||
|
||||
/**
|
||||
* QUnit-style interface:
|
||||
*
|
||||
* suite('Array');
|
||||
*
|
||||
* test('#length', function(){
|
||||
* var arr = [1,2,3];
|
||||
* ok(arr.length == 3);
|
||||
* });
|
||||
*
|
||||
* test('#indexOf()', function(){
|
||||
* var arr = [1,2,3];
|
||||
* ok(arr.indexOf(1) == 0);
|
||||
* ok(arr.indexOf(2) == 1);
|
||||
* ok(arr.indexOf(3) == 2);
|
||||
* });
|
||||
*
|
||||
* suite('String');
|
||||
*
|
||||
* test('#length', function(){
|
||||
* ok('foo'.length == 3);
|
||||
* });
|
||||
*
|
||||
*/
|
||||
|
||||
module.exports = function(suite){
|
||||
var suites = [suite];
|
||||
|
||||
suite.on('pre-require', function(context, file, mocha){
|
||||
|
||||
/**
|
||||
* Execute before running tests.
|
||||
*/
|
||||
|
||||
context.before = function(fn){
|
||||
suites[0].beforeAll(fn);
|
||||
};
|
||||
|
||||
/**
|
||||
* Execute after running tests.
|
||||
*/
|
||||
|
||||
context.after = function(fn){
|
||||
suites[0].afterAll(fn);
|
||||
};
|
||||
|
||||
/**
|
||||
* Execute before each test case.
|
||||
*/
|
||||
|
||||
context.beforeEach = function(fn){
|
||||
suites[0].beforeEach(fn);
|
||||
};
|
||||
|
||||
/**
|
||||
* Execute after each test case.
|
||||
*/
|
||||
|
||||
context.afterEach = function(fn){
|
||||
suites[0].afterEach(fn);
|
||||
};
|
||||
|
||||
/**
|
||||
* Describe a "suite" with the given `title`.
|
||||
*/
|
||||
|
||||
context.suite = function(title){
|
||||
if (suites.length > 1) suites.shift();
|
||||
var suite = Suite.create(suites[0], title);
|
||||
suites.unshift(suite);
|
||||
return suite;
|
||||
};
|
||||
|
||||
/**
|
||||
* Exclusive test-case.
|
||||
*/
|
||||
|
||||
context.suite.only = function(title, fn){
|
||||
var suite = context.suite(title, fn);
|
||||
mocha.grep(suite.fullTitle());
|
||||
};
|
||||
|
||||
/**
|
||||
* Describe a specification or test-case
|
||||
* with the given `title` and callback `fn`
|
||||
* acting as a thunk.
|
||||
*/
|
||||
|
||||
context.test = function(title, fn){
|
||||
var test = new Test(title, fn);
|
||||
suites[0].addTest(test);
|
||||
return test;
|
||||
};
|
||||
|
||||
/**
|
||||
* Exclusive test-case.
|
||||
*/
|
||||
|
||||
context.test.only = function(title, fn){
|
||||
var test = context.test(title, fn);
|
||||
var reString = '^' + utils.escapeRegexp(test.fullTitle()) + '$';
|
||||
mocha.grep(new RegExp(reString));
|
||||
};
|
||||
|
||||
/**
|
||||
* Pending test case.
|
||||
*/
|
||||
|
||||
context.test.skip = function(title){
|
||||
context.test(title);
|
||||
};
|
||||
});
|
||||
};
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var Suite = require('../suite')
|
||||
, Test = require('../test')
|
||||
, utils = require('../utils');;
|
||||
|
||||
/**
|
||||
* TDD-style interface:
|
||||
*
|
||||
* suite('Array', function(){
|
||||
* suite('#indexOf()', function(){
|
||||
* suiteSetup(function(){
|
||||
*
|
||||
* });
|
||||
*
|
||||
* test('should return -1 when not present', function(){
|
||||
*
|
||||
* });
|
||||
*
|
||||
* test('should return the index when present', function(){
|
||||
*
|
||||
* });
|
||||
*
|
||||
* suiteTeardown(function(){
|
||||
*
|
||||
* });
|
||||
* });
|
||||
* });
|
||||
*
|
||||
*/
|
||||
|
||||
module.exports = function(suite){
|
||||
var suites = [suite];
|
||||
|
||||
suite.on('pre-require', function(context, file, mocha){
|
||||
|
||||
/**
|
||||
* Execute before each test case.
|
||||
*/
|
||||
|
||||
context.setup = function(fn){
|
||||
suites[0].beforeEach(fn);
|
||||
};
|
||||
|
||||
/**
|
||||
* Execute after each test case.
|
||||
*/
|
||||
|
||||
context.teardown = function(fn){
|
||||
suites[0].afterEach(fn);
|
||||
};
|
||||
|
||||
/**
|
||||
* Execute before the suite.
|
||||
*/
|
||||
|
||||
context.suiteSetup = function(fn){
|
||||
suites[0].beforeAll(fn);
|
||||
};
|
||||
|
||||
/**
|
||||
* Execute after the suite.
|
||||
*/
|
||||
|
||||
context.suiteTeardown = function(fn){
|
||||
suites[0].afterAll(fn);
|
||||
};
|
||||
|
||||
/**
|
||||
* Describe a "suite" with the given `title`
|
||||
* and callback `fn` containing nested suites
|
||||
* and/or tests.
|
||||
*/
|
||||
|
||||
context.suite = function(title, fn){
|
||||
var suite = Suite.create(suites[0], title);
|
||||
suites.unshift(suite);
|
||||
fn.call(suite);
|
||||
suites.shift();
|
||||
return suite;
|
||||
};
|
||||
|
||||
/**
|
||||
* Pending suite.
|
||||
*/
|
||||
context.suite.skip = function(title, fn) {
|
||||
var suite = Suite.create(suites[0], title);
|
||||
suite.pending = true;
|
||||
suites.unshift(suite);
|
||||
fn.call(suite);
|
||||
suites.shift();
|
||||
};
|
||||
|
||||
/**
|
||||
* Exclusive test-case.
|
||||
*/
|
||||
|
||||
context.suite.only = function(title, fn){
|
||||
var suite = context.suite(title, fn);
|
||||
mocha.grep(suite.fullTitle());
|
||||
};
|
||||
|
||||
/**
|
||||
* Describe a specification or test-case
|
||||
* with the given `title` and callback `fn`
|
||||
* acting as a thunk.
|
||||
*/
|
||||
|
||||
context.test = function(title, fn){
|
||||
var suite = suites[0];
|
||||
if (suite.pending) var fn = null;
|
||||
var test = new Test(title, fn);
|
||||
suite.addTest(test);
|
||||
return test;
|
||||
};
|
||||
|
||||
/**
|
||||
* Exclusive test-case.
|
||||
*/
|
||||
|
||||
context.test.only = function(title, fn){
|
||||
var test = context.test(title, fn);
|
||||
var reString = '^' + utils.escapeRegexp(test.fullTitle()) + '$';
|
||||
mocha.grep(new RegExp(reString));
|
||||
};
|
||||
|
||||
/**
|
||||
* Pending test case.
|
||||
*/
|
||||
|
||||
context.test.skip = function(title){
|
||||
context.test(title);
|
||||
};
|
||||
});
|
||||
};
|
||||
+369
@@ -0,0 +1,369 @@
|
||||
/*!
|
||||
* mocha
|
||||
* Copyright(c) 2011 TJ Holowaychuk <tj@vision-media.ca>
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var path = require('path')
|
||||
, utils = require('./utils');
|
||||
|
||||
/**
|
||||
* Expose `Mocha`.
|
||||
*/
|
||||
|
||||
exports = module.exports = Mocha;
|
||||
|
||||
/**
|
||||
* Expose internals.
|
||||
*/
|
||||
|
||||
exports.utils = utils;
|
||||
exports.interfaces = require('./interfaces');
|
||||
exports.reporters = require('./reporters');
|
||||
exports.Runnable = require('./runnable');
|
||||
exports.Context = require('./context');
|
||||
exports.Runner = require('./runner');
|
||||
exports.Suite = require('./suite');
|
||||
exports.Hook = require('./hook');
|
||||
exports.Test = require('./test');
|
||||
|
||||
/**
|
||||
* Return image `name` path.
|
||||
*
|
||||
* @param {String} name
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function image(name) {
|
||||
return __dirname + '/../images/' + name + '.png';
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup mocha with `options`.
|
||||
*
|
||||
* Options:
|
||||
*
|
||||
* - `ui` name "bdd", "tdd", "exports" etc
|
||||
* - `reporter` reporter instance, defaults to `mocha.reporters.Dot`
|
||||
* - `globals` array of accepted globals
|
||||
* - `timeout` timeout in milliseconds
|
||||
* - `bail` bail on the first test failure
|
||||
* - `slow` milliseconds to wait before considering a test slow
|
||||
* - `ignoreLeaks` ignore global leaks
|
||||
* - `grep` string or regexp to filter tests with
|
||||
*
|
||||
* @param {Object} options
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function Mocha(options) {
|
||||
options = options || {};
|
||||
this.files = [];
|
||||
this.options = options;
|
||||
this.grep(options.grep);
|
||||
this.suite = new exports.Suite('', new exports.Context);
|
||||
this.ui(options.ui);
|
||||
this.bail(options.bail);
|
||||
this.reporter(options.reporter);
|
||||
if (null != options.timeout) this.timeout(options.timeout);
|
||||
this.useColors(options.useColors)
|
||||
if (options.slow) this.slow(options.slow);
|
||||
|
||||
this.suite.on('pre-require', function (context) {
|
||||
exports.afterEach = context.afterEach || context.teardown;
|
||||
exports.after = context.after || context.suiteTeardown;
|
||||
exports.beforeEach = context.beforeEach || context.setup;
|
||||
exports.before = context.before || context.suiteSetup;
|
||||
exports.describe = context.describe || context.suite;
|
||||
exports.it = context.it || context.test;
|
||||
exports.setup = context.setup || context.beforeEach;
|
||||
exports.suiteSetup = context.suiteSetup || context.before;
|
||||
exports.suiteTeardown = context.suiteTeardown || context.after;
|
||||
exports.suite = context.suite || context.describe;
|
||||
exports.teardown = context.teardown || context.afterEach;
|
||||
exports.test = context.test || context.it;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable or disable bailing on the first failure.
|
||||
*
|
||||
* @param {Boolean} [bail]
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mocha.prototype.bail = function(bail){
|
||||
if (0 == arguments.length) bail = true;
|
||||
this.suite.bail(bail);
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add test `file`.
|
||||
*
|
||||
* @param {String} file
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mocha.prototype.addFile = function(file){
|
||||
this.files.push(file);
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Set reporter to `reporter`, defaults to "dot".
|
||||
*
|
||||
* @param {String|Function} reporter name or constructor
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mocha.prototype.reporter = function(reporter){
|
||||
if ('function' == typeof reporter) {
|
||||
this._reporter = reporter;
|
||||
} else {
|
||||
reporter = reporter || 'dot';
|
||||
var _reporter;
|
||||
try { _reporter = require('./reporters/' + reporter); } catch (err) {};
|
||||
if (!_reporter) try { _reporter = require(reporter); } catch (err) {};
|
||||
if (!_reporter && reporter === 'teamcity')
|
||||
console.warn('The Teamcity reporter was moved to a package named ' +
|
||||
'mocha-teamcity-reporter ' +
|
||||
'(https://npmjs.org/package/mocha-teamcity-reporter).');
|
||||
if (!_reporter) throw new Error('invalid reporter "' + reporter + '"');
|
||||
this._reporter = _reporter;
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Set test UI `name`, defaults to "bdd".
|
||||
*
|
||||
* @param {String} bdd
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mocha.prototype.ui = function(name){
|
||||
name = name || 'bdd';
|
||||
this._ui = exports.interfaces[name];
|
||||
if (!this._ui) try { this._ui = require(name); } catch (err) {};
|
||||
if (!this._ui) throw new Error('invalid interface "' + name + '"');
|
||||
this._ui = this._ui(this.suite);
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Load registered files.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Mocha.prototype.loadFiles = function(fn){
|
||||
var self = this;
|
||||
var suite = this.suite;
|
||||
var pending = this.files.length;
|
||||
this.files.forEach(function(file){
|
||||
file = path.resolve(file);
|
||||
suite.emit('pre-require', global, file, self);
|
||||
suite.emit('require', require(file), file, self);
|
||||
suite.emit('post-require', global, file, self);
|
||||
--pending || (fn && fn());
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Enable growl support.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Mocha.prototype._growl = function(runner, reporter) {
|
||||
var notify = require('growl');
|
||||
|
||||
runner.on('end', function(){
|
||||
var stats = reporter.stats;
|
||||
if (stats.failures) {
|
||||
var msg = stats.failures + ' of ' + runner.total + ' tests failed';
|
||||
notify(msg, { name: 'mocha', title: 'Failed', image: image('error') });
|
||||
} else {
|
||||
notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', {
|
||||
name: 'mocha'
|
||||
, title: 'Passed'
|
||||
, image: image('ok')
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Add regexp to grep, if `re` is a string it is escaped.
|
||||
*
|
||||
* @param {RegExp|String} re
|
||||
* @return {Mocha}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mocha.prototype.grep = function(re){
|
||||
this.options.grep = 'string' == typeof re
|
||||
? new RegExp(utils.escapeRegexp(re))
|
||||
: re;
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Invert `.grep()` matches.
|
||||
*
|
||||
* @return {Mocha}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mocha.prototype.invert = function(){
|
||||
this.options.invert = true;
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Ignore global leaks.
|
||||
*
|
||||
* @param {Boolean} ignore
|
||||
* @return {Mocha}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mocha.prototype.ignoreLeaks = function(ignore){
|
||||
this.options.ignoreLeaks = !!ignore;
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Enable global leak checking.
|
||||
*
|
||||
* @return {Mocha}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mocha.prototype.checkLeaks = function(){
|
||||
this.options.ignoreLeaks = false;
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Enable growl support.
|
||||
*
|
||||
* @return {Mocha}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mocha.prototype.growl = function(){
|
||||
this.options.growl = true;
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Ignore `globals` array or string.
|
||||
*
|
||||
* @param {Array|String} globals
|
||||
* @return {Mocha}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mocha.prototype.globals = function(globals){
|
||||
this.options.globals = (this.options.globals || []).concat(globals);
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Emit color output.
|
||||
*
|
||||
* @param {Boolean} colors
|
||||
* @return {Mocha}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mocha.prototype.useColors = function(colors){
|
||||
this.options.useColors = arguments.length && colors != undefined
|
||||
? colors
|
||||
: true;
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Use inline diffs rather than +/-.
|
||||
*
|
||||
* @param {Boolean} inlineDiffs
|
||||
* @return {Mocha}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mocha.prototype.useInlineDiffs = function(inlineDiffs) {
|
||||
this.options.useInlineDiffs = arguments.length && inlineDiffs != undefined
|
||||
? inlineDiffs
|
||||
: false;
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Set the timeout in milliseconds.
|
||||
*
|
||||
* @param {Number} timeout
|
||||
* @return {Mocha}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mocha.prototype.timeout = function(timeout){
|
||||
this.suite.timeout(timeout);
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Set slowness threshold in milliseconds.
|
||||
*
|
||||
* @param {Number} slow
|
||||
* @return {Mocha}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mocha.prototype.slow = function(slow){
|
||||
this.suite.slow(slow);
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Makes all tests async (accepting a callback)
|
||||
*
|
||||
* @return {Mocha}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mocha.prototype.asyncOnly = function(){
|
||||
this.options.asyncOnly = true;
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Run tests and invoke `fn()` when complete.
|
||||
*
|
||||
* @param {Function} fn
|
||||
* @return {Runner}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Mocha.prototype.run = function(fn){
|
||||
if (this.files.length) this.loadFiles();
|
||||
var suite = this.suite;
|
||||
var options = this.options;
|
||||
var runner = new exports.Runner(suite);
|
||||
var reporter = new this._reporter(runner);
|
||||
runner.ignoreLeaks = false !== options.ignoreLeaks;
|
||||
runner.asyncOnly = options.asyncOnly;
|
||||
if (options.grep) runner.grep(options.grep, options.invert);
|
||||
if (options.globals) runner.globals(options.globals);
|
||||
if (options.growl) this._growl(runner, reporter);
|
||||
exports.reporters.Base.useColors = options.useColors;
|
||||
exports.reporters.Base.inlineDiffs = options.useInlineDiffs;
|
||||
return runner.run(fn);
|
||||
};
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* Helpers.
|
||||
*/
|
||||
|
||||
var s = 1000;
|
||||
var m = s * 60;
|
||||
var h = m * 60;
|
||||
var d = h * 24;
|
||||
var y = d * 365.25;
|
||||
|
||||
/**
|
||||
* Parse or format the given `val`.
|
||||
*
|
||||
* Options:
|
||||
*
|
||||
* - `long` verbose formatting [false]
|
||||
*
|
||||
* @param {String|Number} val
|
||||
* @param {Object} options
|
||||
* @return {String|Number}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
module.exports = function(val, options){
|
||||
options = options || {};
|
||||
if ('string' == typeof val) return parse(val);
|
||||
return options.long ? longFormat(val) : shortFormat(val);
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse the given `str` and return milliseconds.
|
||||
*
|
||||
* @param {String} str
|
||||
* @return {Number}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function parse(str) {
|
||||
var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);
|
||||
if (!match) return;
|
||||
var n = parseFloat(match[1]);
|
||||
var type = (match[2] || 'ms').toLowerCase();
|
||||
switch (type) {
|
||||
case 'years':
|
||||
case 'year':
|
||||
case 'y':
|
||||
return n * y;
|
||||
case 'days':
|
||||
case 'day':
|
||||
case 'd':
|
||||
return n * d;
|
||||
case 'hours':
|
||||
case 'hour':
|
||||
case 'h':
|
||||
return n * h;
|
||||
case 'minutes':
|
||||
case 'minute':
|
||||
case 'm':
|
||||
return n * m;
|
||||
case 'seconds':
|
||||
case 'second':
|
||||
case 's':
|
||||
return n * s;
|
||||
case 'ms':
|
||||
return n;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Short format for `ms`.
|
||||
*
|
||||
* @param {Number} ms
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function shortFormat(ms) {
|
||||
if (ms >= d) return Math.round(ms / d) + 'd';
|
||||
if (ms >= h) return Math.round(ms / h) + 'h';
|
||||
if (ms >= m) return Math.round(ms / m) + 'm';
|
||||
if (ms >= s) return Math.round(ms / s) + 's';
|
||||
return ms + 'ms';
|
||||
}
|
||||
|
||||
/**
|
||||
* Long format for `ms`.
|
||||
*
|
||||
* @param {Number} ms
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function longFormat(ms) {
|
||||
return plural(ms, d, 'day')
|
||||
|| plural(ms, h, 'hour')
|
||||
|| plural(ms, m, 'minute')
|
||||
|| plural(ms, s, 'second')
|
||||
|| ms + ' ms';
|
||||
}
|
||||
|
||||
/**
|
||||
* Pluralization helper.
|
||||
*/
|
||||
|
||||
function plural(ms, n, name) {
|
||||
if (ms < n) return;
|
||||
if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
|
||||
return Math.ceil(ms / n) + ' ' + name + 's';
|
||||
}
|
||||
+507
@@ -0,0 +1,507 @@
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var tty = require('tty')
|
||||
, diff = require('diff')
|
||||
, ms = require('../ms')
|
||||
, utils = require('../utils');
|
||||
|
||||
/**
|
||||
* Save timer references to avoid Sinon interfering (see GH-237).
|
||||
*/
|
||||
|
||||
var Date = global.Date
|
||||
, setTimeout = global.setTimeout
|
||||
, setInterval = global.setInterval
|
||||
, clearTimeout = global.clearTimeout
|
||||
, clearInterval = global.clearInterval;
|
||||
|
||||
/**
|
||||
* Check if both stdio streams are associated with a tty.
|
||||
*/
|
||||
|
||||
var isatty = tty.isatty(1) && tty.isatty(2);
|
||||
|
||||
/**
|
||||
* Expose `Base`.
|
||||
*/
|
||||
|
||||
exports = module.exports = Base;
|
||||
|
||||
/**
|
||||
* Enable coloring by default.
|
||||
*/
|
||||
|
||||
exports.useColors = isatty || (process.env.MOCHA_COLORS !== undefined);
|
||||
|
||||
/**
|
||||
* Inline diffs instead of +/-
|
||||
*/
|
||||
|
||||
exports.inlineDiffs = false;
|
||||
|
||||
/**
|
||||
* Default color map.
|
||||
*/
|
||||
|
||||
exports.colors = {
|
||||
'pass': 90
|
||||
, 'fail': 31
|
||||
, 'bright pass': 92
|
||||
, 'bright fail': 91
|
||||
, 'bright yellow': 93
|
||||
, 'pending': 36
|
||||
, 'suite': 0
|
||||
, 'error title': 0
|
||||
, 'error message': 31
|
||||
, 'error stack': 90
|
||||
, 'checkmark': 32
|
||||
, 'fast': 90
|
||||
, 'medium': 33
|
||||
, 'slow': 31
|
||||
, 'green': 32
|
||||
, 'light': 90
|
||||
, 'diff gutter': 90
|
||||
, 'diff added': 42
|
||||
, 'diff removed': 41
|
||||
};
|
||||
|
||||
/**
|
||||
* Default symbol map.
|
||||
*/
|
||||
|
||||
exports.symbols = {
|
||||
ok: '✓',
|
||||
err: '✖',
|
||||
dot: '․'
|
||||
};
|
||||
|
||||
// With node.js on Windows: use symbols available in terminal default fonts
|
||||
if ('win32' == process.platform) {
|
||||
exports.symbols.ok = '\u221A';
|
||||
exports.symbols.err = '\u00D7';
|
||||
exports.symbols.dot = '.';
|
||||
}
|
||||
|
||||
/**
|
||||
* Color `str` with the given `type`,
|
||||
* allowing colors to be disabled,
|
||||
* as well as user-defined color
|
||||
* schemes.
|
||||
*
|
||||
* @param {String} type
|
||||
* @param {String} str
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
var color = exports.color = function(type, str) {
|
||||
if (!exports.useColors) return str;
|
||||
return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m';
|
||||
};
|
||||
|
||||
/**
|
||||
* Expose term window size, with some
|
||||
* defaults for when stderr is not a tty.
|
||||
*/
|
||||
|
||||
exports.window = {
|
||||
width: isatty
|
||||
? process.stdout.getWindowSize
|
||||
? process.stdout.getWindowSize(1)[0]
|
||||
: tty.getWindowSize()[1]
|
||||
: 75
|
||||
};
|
||||
|
||||
/**
|
||||
* Expose some basic cursor interactions
|
||||
* that are common among reporters.
|
||||
*/
|
||||
|
||||
exports.cursor = {
|
||||
hide: function(){
|
||||
isatty && process.stdout.write('\u001b[?25l');
|
||||
},
|
||||
|
||||
show: function(){
|
||||
isatty && process.stdout.write('\u001b[?25h');
|
||||
},
|
||||
|
||||
deleteLine: function(){
|
||||
isatty && process.stdout.write('\u001b[2K');
|
||||
},
|
||||
|
||||
beginningOfLine: function(){
|
||||
isatty && process.stdout.write('\u001b[0G');
|
||||
},
|
||||
|
||||
CR: function(){
|
||||
if (isatty) {
|
||||
exports.cursor.deleteLine();
|
||||
exports.cursor.beginningOfLine();
|
||||
} else {
|
||||
process.stdout.write('\r');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Outut the given `failures` as a list.
|
||||
*
|
||||
* @param {Array} failures
|
||||
* @api public
|
||||
*/
|
||||
|
||||
exports.list = function(failures){
|
||||
console.error();
|
||||
failures.forEach(function(test, i){
|
||||
// format
|
||||
var fmt = color('error title', ' %s) %s:\n')
|
||||
+ color('error message', ' %s')
|
||||
+ color('error stack', '\n%s\n');
|
||||
|
||||
// msg
|
||||
var err = test.err
|
||||
, message = err.message || ''
|
||||
, stack = err.stack || message
|
||||
, index = stack.indexOf(message) + message.length
|
||||
, msg = stack.slice(0, index)
|
||||
, actual = err.actual
|
||||
, expected = err.expected
|
||||
, escape = true;
|
||||
|
||||
// uncaught
|
||||
if (err.uncaught) {
|
||||
msg = 'Uncaught ' + msg;
|
||||
}
|
||||
|
||||
// explicitly show diff
|
||||
if (err.showDiff && sameType(actual, expected)) {
|
||||
escape = false;
|
||||
err.actual = actual = stringify(canonicalize(actual));
|
||||
err.expected = expected = stringify(canonicalize(expected));
|
||||
}
|
||||
|
||||
// actual / expected diff
|
||||
if ('string' == typeof actual && 'string' == typeof expected) {
|
||||
fmt = color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n');
|
||||
var match = message.match(/^([^:]+): expected/);
|
||||
msg = '\n ' + color('error message', match ? match[1] : msg);
|
||||
|
||||
if (exports.inlineDiffs) {
|
||||
msg += inlineDiff(err, escape);
|
||||
} else {
|
||||
msg += unifiedDiff(err, escape);
|
||||
}
|
||||
}
|
||||
|
||||
// indent stack trace without msg
|
||||
stack = stack.slice(index ? index + 1 : index)
|
||||
.replace(/^/gm, ' ');
|
||||
|
||||
console.error(fmt, (i + 1), test.fullTitle(), msg, stack);
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Initialize a new `Base` reporter.
|
||||
*
|
||||
* All other reporters generally
|
||||
* inherit from this reporter, providing
|
||||
* stats such as test duration, number
|
||||
* of tests passed / failed etc.
|
||||
*
|
||||
* @param {Runner} runner
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function Base(runner) {
|
||||
var self = this
|
||||
, stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 }
|
||||
, failures = this.failures = [];
|
||||
|
||||
if (!runner) return;
|
||||
this.runner = runner;
|
||||
|
||||
runner.stats = stats;
|
||||
|
||||
runner.on('start', function(){
|
||||
stats.start = new Date;
|
||||
});
|
||||
|
||||
runner.on('suite', function(suite){
|
||||
stats.suites = stats.suites || 0;
|
||||
suite.root || stats.suites++;
|
||||
});
|
||||
|
||||
runner.on('test end', function(test){
|
||||
stats.tests = stats.tests || 0;
|
||||
stats.tests++;
|
||||
});
|
||||
|
||||
runner.on('pass', function(test){
|
||||
stats.passes = stats.passes || 0;
|
||||
|
||||
var medium = test.slow() / 2;
|
||||
test.speed = test.duration > test.slow()
|
||||
? 'slow'
|
||||
: test.duration > medium
|
||||
? 'medium'
|
||||
: 'fast';
|
||||
|
||||
stats.passes++;
|
||||
});
|
||||
|
||||
runner.on('fail', function(test, err){
|
||||
stats.failures = stats.failures || 0;
|
||||
stats.failures++;
|
||||
test.err = err;
|
||||
failures.push(test);
|
||||
});
|
||||
|
||||
runner.on('end', function(){
|
||||
stats.end = new Date;
|
||||
stats.duration = new Date - stats.start;
|
||||
});
|
||||
|
||||
runner.on('pending', function(){
|
||||
stats.pending++;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Output common epilogue used by many of
|
||||
* the bundled reporters.
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Base.prototype.epilogue = function(){
|
||||
var stats = this.stats;
|
||||
var tests;
|
||||
var fmt;
|
||||
|
||||
console.log();
|
||||
|
||||
// passes
|
||||
fmt = color('bright pass', ' ')
|
||||
+ color('green', ' %d passing')
|
||||
+ color('light', ' (%s)');
|
||||
|
||||
console.log(fmt,
|
||||
stats.passes || 0,
|
||||
ms(stats.duration));
|
||||
|
||||
// pending
|
||||
if (stats.pending) {
|
||||
fmt = color('pending', ' ')
|
||||
+ color('pending', ' %d pending');
|
||||
|
||||
console.log(fmt, stats.pending);
|
||||
}
|
||||
|
||||
// failures
|
||||
if (stats.failures) {
|
||||
fmt = color('fail', ' %d failing');
|
||||
|
||||
console.error(fmt,
|
||||
stats.failures);
|
||||
|
||||
Base.list(this.failures);
|
||||
console.error();
|
||||
}
|
||||
|
||||
console.log();
|
||||
};
|
||||
|
||||
/**
|
||||
* Pad the given `str` to `len`.
|
||||
*
|
||||
* @param {String} str
|
||||
* @param {String} len
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function pad(str, len) {
|
||||
str = String(str);
|
||||
return Array(len - str.length + 1).join(' ') + str;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns an inline diff between 2 strings with coloured ANSI output
|
||||
*
|
||||
* @param {Error} Error with actual/expected
|
||||
* @return {String} Diff
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function inlineDiff(err, escape) {
|
||||
var msg = errorDiff(err, 'WordsWithSpace', escape);
|
||||
|
||||
// linenos
|
||||
var lines = msg.split('\n');
|
||||
if (lines.length > 4) {
|
||||
var width = String(lines.length).length;
|
||||
msg = lines.map(function(str, i){
|
||||
return pad(++i, width) + ' |' + ' ' + str;
|
||||
}).join('\n');
|
||||
}
|
||||
|
||||
// legend
|
||||
msg = '\n'
|
||||
+ color('diff removed', 'actual')
|
||||
+ ' '
|
||||
+ color('diff added', 'expected')
|
||||
+ '\n\n'
|
||||
+ msg
|
||||
+ '\n';
|
||||
|
||||
// indent
|
||||
msg = msg.replace(/^/gm, ' ');
|
||||
return msg;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a unified diff between 2 strings
|
||||
*
|
||||
* @param {Error} Error with actual/expected
|
||||
* @return {String} Diff
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function unifiedDiff(err, escape) {
|
||||
var indent = ' ';
|
||||
function cleanUp(line) {
|
||||
if (escape) {
|
||||
line = escapeInvisibles(line);
|
||||
}
|
||||
if (line[0] === '+') return indent + colorLines('diff added', line);
|
||||
if (line[0] === '-') return indent + colorLines('diff removed', line);
|
||||
if (line.match(/\@\@/)) return null;
|
||||
if (line.match(/\\ No newline/)) return null;
|
||||
else return indent + line;
|
||||
}
|
||||
function notBlank(line) {
|
||||
return line != null;
|
||||
}
|
||||
msg = diff.createPatch('string', err.actual, err.expected);
|
||||
var lines = msg.split('\n').splice(4);
|
||||
return '\n '
|
||||
+ colorLines('diff added', '+ expected') + ' '
|
||||
+ colorLines('diff removed', '- actual')
|
||||
+ '\n\n'
|
||||
+ lines.map(cleanUp).filter(notBlank).join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a character diff for `err`.
|
||||
*
|
||||
* @param {Error} err
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function errorDiff(err, type, escape) {
|
||||
var actual = escape ? escapeInvisibles(err.actual) : err.actual;
|
||||
var expected = escape ? escapeInvisibles(err.expected) : err.expected;
|
||||
return diff['diff' + type](actual, expected).map(function(str){
|
||||
if (str.added) return colorLines('diff added', str.value);
|
||||
if (str.removed) return colorLines('diff removed', str.value);
|
||||
return str.value;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a string with all invisible characters in plain text
|
||||
*
|
||||
* @param {String} line
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
function escapeInvisibles(line) {
|
||||
return line.replace(/\t/g, '<tab>')
|
||||
.replace(/\r/g, '<CR>')
|
||||
.replace(/\n/g, '<LF>\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Color lines for `str`, using the color `name`.
|
||||
*
|
||||
* @param {String} name
|
||||
* @param {String} str
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function colorLines(name, str) {
|
||||
return str.split('\n').map(function(str){
|
||||
return color(name, str);
|
||||
}).join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Stringify `obj`.
|
||||
*
|
||||
* @param {Object} obj
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function stringify(obj) {
|
||||
if (obj instanceof RegExp) return obj.toString();
|
||||
return JSON.stringify(obj, null, 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a new object that has the keys in sorted order.
|
||||
* @param {Object} obj
|
||||
* @return {Object}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function canonicalize(obj, stack) {
|
||||
stack = stack || [];
|
||||
|
||||
if (utils.indexOf(stack, obj) !== -1) return obj;
|
||||
|
||||
var canonicalizedObj;
|
||||
|
||||
if ('[object Array]' == {}.toString.call(obj)) {
|
||||
stack.push(obj);
|
||||
canonicalizedObj = utils.map(obj, function(item) {
|
||||
return canonicalize(item, stack);
|
||||
});
|
||||
stack.pop();
|
||||
} else if (typeof obj === 'object' && obj !== null) {
|
||||
stack.push(obj);
|
||||
canonicalizedObj = {};
|
||||
utils.forEach(utils.keys(obj).sort(), function(key) {
|
||||
canonicalizedObj[key] = canonicalize(obj[key], stack);
|
||||
});
|
||||
stack.pop();
|
||||
} else {
|
||||
canonicalizedObj = obj;
|
||||
}
|
||||
|
||||
return canonicalizedObj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that a / b have the same type.
|
||||
*
|
||||
* @param {Object} a
|
||||
* @param {Object} b
|
||||
* @return {Boolean}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function sameType(a, b) {
|
||||
a = Object.prototype.toString.call(a);
|
||||
b = Object.prototype.toString.call(b);
|
||||
return a == b;
|
||||
}
|
||||
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var Base = require('./base')
|
||||
, utils = require('../utils');
|
||||
|
||||
/**
|
||||
* Expose `Doc`.
|
||||
*/
|
||||
|
||||
exports = module.exports = Doc;
|
||||
|
||||
/**
|
||||
* Initialize a new `Doc` reporter.
|
||||
*
|
||||
* @param {Runner} runner
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function Doc(runner) {
|
||||
Base.call(this, runner);
|
||||
|
||||
var self = this
|
||||
, stats = this.stats
|
||||
, total = runner.total
|
||||
, indents = 2;
|
||||
|
||||
function indent() {
|
||||
return Array(indents).join(' ');
|
||||
}
|
||||
|
||||
runner.on('suite', function(suite){
|
||||
if (suite.root) return;
|
||||
++indents;
|
||||
console.log('%s<section class="suite">', indent());
|
||||
++indents;
|
||||
console.log('%s<h1>%s</h1>', indent(), utils.escape(suite.title));
|
||||
console.log('%s<dl>', indent());
|
||||
});
|
||||
|
||||
runner.on('suite end', function(suite){
|
||||
if (suite.root) return;
|
||||
console.log('%s</dl>', indent());
|
||||
--indents;
|
||||
console.log('%s</section>', indent());
|
||||
--indents;
|
||||
});
|
||||
|
||||
runner.on('pass', function(test){
|
||||
console.log('%s <dt>%s</dt>', indent(), utils.escape(test.title));
|
||||
var code = utils.escape(utils.clean(test.fn.toString()));
|
||||
console.log('%s <dd><pre><code>%s</code></pre></dd>', indent(), code);
|
||||
});
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var Base = require('./base')
|
||||
, color = Base.color;
|
||||
|
||||
/**
|
||||
* Expose `Dot`.
|
||||
*/
|
||||
|
||||
exports = module.exports = Dot;
|
||||
|
||||
/**
|
||||
* Initialize a new `Dot` matrix test reporter.
|
||||
*
|
||||
* @param {Runner} runner
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function Dot(runner) {
|
||||
Base.call(this, runner);
|
||||
|
||||
var self = this
|
||||
, stats = this.stats
|
||||
, width = Base.window.width * .75 | 0
|
||||
, n = 0;
|
||||
|
||||
runner.on('start', function(){
|
||||
process.stdout.write('\n ');
|
||||
});
|
||||
|
||||
runner.on('pending', function(test){
|
||||
process.stdout.write(color('pending', Base.symbols.dot));
|
||||
});
|
||||
|
||||
runner.on('pass', function(test){
|
||||
if (++n % width == 0) process.stdout.write('\n ');
|
||||
if ('slow' == test.speed) {
|
||||
process.stdout.write(color('bright yellow', Base.symbols.dot));
|
||||
} else {
|
||||
process.stdout.write(color(test.speed, Base.symbols.dot));
|
||||
}
|
||||
});
|
||||
|
||||
runner.on('fail', function(test, err){
|
||||
if (++n % width == 0) process.stdout.write('\n ');
|
||||
process.stdout.write(color('fail', Base.symbols.dot));
|
||||
});
|
||||
|
||||
runner.on('end', function(){
|
||||
console.log();
|
||||
self.epilogue();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Inherit from `Base.prototype`.
|
||||
*/
|
||||
|
||||
Dot.prototype.__proto__ = Base.prototype;
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var JSONCov = require('./json-cov')
|
||||
, fs = require('fs');
|
||||
|
||||
/**
|
||||
* Expose `HTMLCov`.
|
||||
*/
|
||||
|
||||
exports = module.exports = HTMLCov;
|
||||
|
||||
/**
|
||||
* Initialize a new `JsCoverage` reporter.
|
||||
*
|
||||
* @param {Runner} runner
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function HTMLCov(runner) {
|
||||
var jade = require('jade')
|
||||
, file = __dirname + '/templates/coverage.jade'
|
||||
, str = fs.readFileSync(file, 'utf8')
|
||||
, fn = jade.compile(str, { filename: file })
|
||||
, self = this;
|
||||
|
||||
JSONCov.call(this, runner, false);
|
||||
|
||||
runner.on('end', function(){
|
||||
process.stdout.write(fn({
|
||||
cov: self.cov
|
||||
, coverageClass: coverageClass
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Return coverage class for `n`.
|
||||
*
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function coverageClass(n) {
|
||||
if (n >= 75) return 'high';
|
||||
if (n >= 50) return 'medium';
|
||||
if (n >= 25) return 'low';
|
||||
return 'terrible';
|
||||
}
|
||||
+274
@@ -0,0 +1,274 @@
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var Base = require('./base')
|
||||
, utils = require('../utils')
|
||||
, Progress = require('../browser/progress')
|
||||
, escape = utils.escape;
|
||||
|
||||
/**
|
||||
* Save timer references to avoid Sinon interfering (see GH-237).
|
||||
*/
|
||||
|
||||
var Date = global.Date
|
||||
, setTimeout = global.setTimeout
|
||||
, setInterval = global.setInterval
|
||||
, clearTimeout = global.clearTimeout
|
||||
, clearInterval = global.clearInterval;
|
||||
|
||||
/**
|
||||
* Expose `HTML`.
|
||||
*/
|
||||
|
||||
exports = module.exports = HTML;
|
||||
|
||||
/**
|
||||
* Stats template.
|
||||
*/
|
||||
|
||||
var statsTemplate = '<ul id="mocha-stats">'
|
||||
+ '<li class="progress"><canvas width="40" height="40"></canvas></li>'
|
||||
+ '<li class="passes"><a href="#">passes:</a> <em>0</em></li>'
|
||||
+ '<li class="failures"><a href="#">failures:</a> <em>0</em></li>'
|
||||
+ '<li class="duration">duration: <em>0</em>s</li>'
|
||||
+ '</ul>';
|
||||
|
||||
/**
|
||||
* Initialize a new `HTML` reporter.
|
||||
*
|
||||
* @param {Runner} runner
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function HTML(runner, root) {
|
||||
Base.call(this, runner);
|
||||
|
||||
var self = this
|
||||
, stats = this.stats
|
||||
, total = runner.total
|
||||
, stat = fragment(statsTemplate)
|
||||
, items = stat.getElementsByTagName('li')
|
||||
, passes = items[1].getElementsByTagName('em')[0]
|
||||
, passesLink = items[1].getElementsByTagName('a')[0]
|
||||
, failures = items[2].getElementsByTagName('em')[0]
|
||||
, failuresLink = items[2].getElementsByTagName('a')[0]
|
||||
, duration = items[3].getElementsByTagName('em')[0]
|
||||
, canvas = stat.getElementsByTagName('canvas')[0]
|
||||
, report = fragment('<ul id="mocha-report"></ul>')
|
||||
, stack = [report]
|
||||
, progress
|
||||
, ctx
|
||||
|
||||
root = root || document.getElementById('mocha');
|
||||
|
||||
if (canvas.getContext) {
|
||||
var ratio = window.devicePixelRatio || 1;
|
||||
canvas.style.width = canvas.width;
|
||||
canvas.style.height = canvas.height;
|
||||
canvas.width *= ratio;
|
||||
canvas.height *= ratio;
|
||||
ctx = canvas.getContext('2d');
|
||||
ctx.scale(ratio, ratio);
|
||||
progress = new Progress;
|
||||
}
|
||||
|
||||
if (!root) return error('#mocha div missing, add it to your document');
|
||||
|
||||
// pass toggle
|
||||
on(passesLink, 'click', function(){
|
||||
unhide();
|
||||
var name = /pass/.test(report.className) ? '' : ' pass';
|
||||
report.className = report.className.replace(/fail|pass/g, '') + name;
|
||||
if (report.className.trim()) hideSuitesWithout('test pass');
|
||||
});
|
||||
|
||||
// failure toggle
|
||||
on(failuresLink, 'click', function(){
|
||||
unhide();
|
||||
var name = /fail/.test(report.className) ? '' : ' fail';
|
||||
report.className = report.className.replace(/fail|pass/g, '') + name;
|
||||
if (report.className.trim()) hideSuitesWithout('test fail');
|
||||
});
|
||||
|
||||
root.appendChild(stat);
|
||||
root.appendChild(report);
|
||||
|
||||
if (progress) progress.size(40);
|
||||
|
||||
runner.on('suite', function(suite){
|
||||
if (suite.root) return;
|
||||
|
||||
// suite
|
||||
var url = self.suiteURL(suite);
|
||||
var el = fragment('<li class="suite"><h1><a href="%s">%s</a></h1></li>', url, escape(suite.title));
|
||||
|
||||
// container
|
||||
stack[0].appendChild(el);
|
||||
stack.unshift(document.createElement('ul'));
|
||||
el.appendChild(stack[0]);
|
||||
});
|
||||
|
||||
runner.on('suite end', function(suite){
|
||||
if (suite.root) return;
|
||||
stack.shift();
|
||||
});
|
||||
|
||||
runner.on('fail', function(test, err){
|
||||
if ('hook' == test.type) runner.emit('test end', test);
|
||||
});
|
||||
|
||||
runner.on('test end', function(test){
|
||||
// TODO: add to stats
|
||||
var percent = stats.tests / this.total * 100 | 0;
|
||||
if (progress) progress.update(percent).draw(ctx);
|
||||
|
||||
// update stats
|
||||
var ms = new Date - stats.start;
|
||||
text(passes, stats.passes);
|
||||
text(failures, stats.failures);
|
||||
text(duration, (ms / 1000).toFixed(2));
|
||||
|
||||
// test
|
||||
if ('passed' == test.state) {
|
||||
var url = self.testURL(test);
|
||||
var el = fragment('<li class="test pass %e"><h2>%e<span class="duration">%ems</span> <a href="%s" class="replay">‣</a></h2></li>', test.speed, test.title, test.duration, url);
|
||||
} else if (test.pending) {
|
||||
var el = fragment('<li class="test pass pending"><h2>%e</h2></li>', test.title);
|
||||
} else {
|
||||
var el = fragment('<li class="test fail"><h2>%e <a href="?grep=%e" class="replay">‣</a></h2></li>', test.title, encodeURIComponent(test.fullTitle()));
|
||||
var str = test.err.stack || test.err.toString();
|
||||
|
||||
// FF / Opera do not add the message
|
||||
if (!~str.indexOf(test.err.message)) {
|
||||
str = test.err.message + '\n' + str;
|
||||
}
|
||||
|
||||
// <=IE7 stringifies to [Object Error]. Since it can be overloaded, we
|
||||
// check for the result of the stringifying.
|
||||
if ('[object Error]' == str) str = test.err.message;
|
||||
|
||||
// Safari doesn't give you a stack. Let's at least provide a source line.
|
||||
if (!test.err.stack && test.err.sourceURL && test.err.line !== undefined) {
|
||||
str += "\n(" + test.err.sourceURL + ":" + test.err.line + ")";
|
||||
}
|
||||
|
||||
el.appendChild(fragment('<pre class="error">%e</pre>', str));
|
||||
}
|
||||
|
||||
// toggle code
|
||||
// TODO: defer
|
||||
if (!test.pending) {
|
||||
var h2 = el.getElementsByTagName('h2')[0];
|
||||
|
||||
on(h2, 'click', function(){
|
||||
pre.style.display = 'none' == pre.style.display
|
||||
? 'block'
|
||||
: 'none';
|
||||
});
|
||||
|
||||
var pre = fragment('<pre><code>%e</code></pre>', utils.clean(test.fn.toString()));
|
||||
el.appendChild(pre);
|
||||
pre.style.display = 'none';
|
||||
}
|
||||
|
||||
// Don't call .appendChild if #mocha-report was already .shift()'ed off the stack.
|
||||
if (stack[0]) stack[0].appendChild(el);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Provide suite URL
|
||||
*
|
||||
* @param {Object} [suite]
|
||||
*/
|
||||
|
||||
HTML.prototype.suiteURL = function(suite){
|
||||
return '?grep=' + encodeURIComponent(suite.fullTitle());
|
||||
};
|
||||
|
||||
/**
|
||||
* Provide test URL
|
||||
*
|
||||
* @param {Object} [test]
|
||||
*/
|
||||
|
||||
HTML.prototype.testURL = function(test){
|
||||
return '?grep=' + encodeURIComponent(test.fullTitle());
|
||||
};
|
||||
|
||||
/**
|
||||
* Display error `msg`.
|
||||
*/
|
||||
|
||||
function error(msg) {
|
||||
document.body.appendChild(fragment('<div id="mocha-error">%s</div>', msg));
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a DOM fragment from `html`.
|
||||
*/
|
||||
|
||||
function fragment(html) {
|
||||
var args = arguments
|
||||
, div = document.createElement('div')
|
||||
, i = 1;
|
||||
|
||||
div.innerHTML = html.replace(/%([se])/g, function(_, type){
|
||||
switch (type) {
|
||||
case 's': return String(args[i++]);
|
||||
case 'e': return escape(args[i++]);
|
||||
}
|
||||
});
|
||||
|
||||
return div.firstChild;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check for suites that do not have elements
|
||||
* with `classname`, and hide them.
|
||||
*/
|
||||
|
||||
function hideSuitesWithout(classname) {
|
||||
var suites = document.getElementsByClassName('suite');
|
||||
for (var i = 0; i < suites.length; i++) {
|
||||
var els = suites[i].getElementsByClassName(classname);
|
||||
if (0 == els.length) suites[i].className += ' hidden';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unhide .hidden suites.
|
||||
*/
|
||||
|
||||
function unhide() {
|
||||
var els = document.getElementsByClassName('suite hidden');
|
||||
for (var i = 0; i < els.length; ++i) {
|
||||
els[i].className = els[i].className.replace('suite hidden', 'suite');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set `el` text to `str`.
|
||||
*/
|
||||
|
||||
function text(el, str) {
|
||||
if (el.textContent) {
|
||||
el.textContent = str;
|
||||
} else {
|
||||
el.innerText = str;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Listen on `event` with callback `fn`.
|
||||
*/
|
||||
|
||||
function on(el, event, fn) {
|
||||
if (el.addEventListener) {
|
||||
el.addEventListener(event, fn, false);
|
||||
} else {
|
||||
el.attachEvent('on' + event, fn);
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
|
||||
exports.Base = require('./base');
|
||||
exports.Dot = require('./dot');
|
||||
exports.Doc = require('./doc');
|
||||
exports.TAP = require('./tap');
|
||||
exports.JSON = require('./json');
|
||||
exports.HTML = require('./html');
|
||||
exports.List = require('./list');
|
||||
exports.Min = require('./min');
|
||||
exports.Spec = require('./spec');
|
||||
exports.Nyan = require('./nyan');
|
||||
exports.XUnit = require('./xunit');
|
||||
exports.Markdown = require('./markdown');
|
||||
exports.Progress = require('./progress');
|
||||
exports.Landing = require('./landing');
|
||||
exports.JSONCov = require('./json-cov');
|
||||
exports.HTMLCov = require('./html-cov');
|
||||
exports.JSONStream = require('./json-stream');
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var Base = require('./base');
|
||||
|
||||
/**
|
||||
* Expose `JSONCov`.
|
||||
*/
|
||||
|
||||
exports = module.exports = JSONCov;
|
||||
|
||||
/**
|
||||
* Initialize a new `JsCoverage` reporter.
|
||||
*
|
||||
* @param {Runner} runner
|
||||
* @param {Boolean} output
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function JSONCov(runner, output) {
|
||||
var self = this
|
||||
, output = 1 == arguments.length ? true : output;
|
||||
|
||||
Base.call(this, runner);
|
||||
|
||||
var tests = []
|
||||
, failures = []
|
||||
, passes = [];
|
||||
|
||||
runner.on('test end', function(test){
|
||||
tests.push(test);
|
||||
});
|
||||
|
||||
runner.on('pass', function(test){
|
||||
passes.push(test);
|
||||
});
|
||||
|
||||
runner.on('fail', function(test){
|
||||
failures.push(test);
|
||||
});
|
||||
|
||||
runner.on('end', function(){
|
||||
var cov = global._$jscoverage || {};
|
||||
var result = self.cov = map(cov);
|
||||
result.stats = self.stats;
|
||||
result.tests = tests.map(clean);
|
||||
result.failures = failures.map(clean);
|
||||
result.passes = passes.map(clean);
|
||||
if (!output) return;
|
||||
process.stdout.write(JSON.stringify(result, null, 2 ));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Map jscoverage data to a JSON structure
|
||||
* suitable for reporting.
|
||||
*
|
||||
* @param {Object} cov
|
||||
* @return {Object}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function map(cov) {
|
||||
var ret = {
|
||||
instrumentation: 'node-jscoverage'
|
||||
, sloc: 0
|
||||
, hits: 0
|
||||
, misses: 0
|
||||
, coverage: 0
|
||||
, files: []
|
||||
};
|
||||
|
||||
for (var filename in cov) {
|
||||
var data = coverage(filename, cov[filename]);
|
||||
ret.files.push(data);
|
||||
ret.hits += data.hits;
|
||||
ret.misses += data.misses;
|
||||
ret.sloc += data.sloc;
|
||||
}
|
||||
|
||||
ret.files.sort(function(a, b) {
|
||||
return a.filename.localeCompare(b.filename);
|
||||
});
|
||||
|
||||
if (ret.sloc > 0) {
|
||||
ret.coverage = (ret.hits / ret.sloc) * 100;
|
||||
}
|
||||
|
||||
return ret;
|
||||
};
|
||||
|
||||
/**
|
||||
* Map jscoverage data for a single source file
|
||||
* to a JSON structure suitable for reporting.
|
||||
*
|
||||
* @param {String} filename name of the source file
|
||||
* @param {Object} data jscoverage coverage data
|
||||
* @return {Object}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function coverage(filename, data) {
|
||||
var ret = {
|
||||
filename: filename,
|
||||
coverage: 0,
|
||||
hits: 0,
|
||||
misses: 0,
|
||||
sloc: 0,
|
||||
source: {}
|
||||
};
|
||||
|
||||
data.source.forEach(function(line, num){
|
||||
num++;
|
||||
|
||||
if (data[num] === 0) {
|
||||
ret.misses++;
|
||||
ret.sloc++;
|
||||
} else if (data[num] !== undefined) {
|
||||
ret.hits++;
|
||||
ret.sloc++;
|
||||
}
|
||||
|
||||
ret.source[num] = {
|
||||
source: line
|
||||
, coverage: data[num] === undefined
|
||||
? ''
|
||||
: data[num]
|
||||
};
|
||||
});
|
||||
|
||||
ret.coverage = ret.hits / ret.sloc * 100;
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a plain-object representation of `test`
|
||||
* free of cyclic properties etc.
|
||||
*
|
||||
* @param {Object} test
|
||||
* @return {Object}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function clean(test) {
|
||||
return {
|
||||
title: test.title
|
||||
, fullTitle: test.fullTitle()
|
||||
, duration: test.duration
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var Base = require('./base')
|
||||
, color = Base.color;
|
||||
|
||||
/**
|
||||
* Expose `List`.
|
||||
*/
|
||||
|
||||
exports = module.exports = List;
|
||||
|
||||
/**
|
||||
* Initialize a new `List` test reporter.
|
||||
*
|
||||
* @param {Runner} runner
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function List(runner) {
|
||||
Base.call(this, runner);
|
||||
|
||||
var self = this
|
||||
, stats = this.stats
|
||||
, total = runner.total;
|
||||
|
||||
runner.on('start', function(){
|
||||
console.log(JSON.stringify(['start', { total: total }]));
|
||||
});
|
||||
|
||||
runner.on('pass', function(test){
|
||||
console.log(JSON.stringify(['pass', clean(test)]));
|
||||
});
|
||||
|
||||
runner.on('fail', function(test, err){
|
||||
console.log(JSON.stringify(['fail', clean(test)]));
|
||||
});
|
||||
|
||||
runner.on('end', function(){
|
||||
process.stdout.write(JSON.stringify(['end', self.stats]));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a plain-object representation of `test`
|
||||
* free of cyclic properties etc.
|
||||
*
|
||||
* @param {Object} test
|
||||
* @return {Object}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function clean(test) {
|
||||
return {
|
||||
title: test.title
|
||||
, fullTitle: test.fullTitle()
|
||||
, duration: test.duration
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var Base = require('./base')
|
||||
, cursor = Base.cursor
|
||||
, color = Base.color;
|
||||
|
||||
/**
|
||||
* Expose `JSON`.
|
||||
*/
|
||||
|
||||
exports = module.exports = JSONReporter;
|
||||
|
||||
/**
|
||||
* Initialize a new `JSON` reporter.
|
||||
*
|
||||
* @param {Runner} runner
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function JSONReporter(runner) {
|
||||
var self = this;
|
||||
Base.call(this, runner);
|
||||
|
||||
var tests = []
|
||||
, failures = []
|
||||
, passes = [];
|
||||
|
||||
runner.on('test end', function(test){
|
||||
tests.push(test);
|
||||
});
|
||||
|
||||
runner.on('pass', function(test){
|
||||
passes.push(test);
|
||||
});
|
||||
|
||||
runner.on('fail', function(test){
|
||||
failures.push(test);
|
||||
});
|
||||
|
||||
runner.on('end', function(){
|
||||
var obj = {
|
||||
stats: self.stats
|
||||
, tests: tests.map(clean)
|
||||
, failures: failures.map(clean)
|
||||
, passes: passes.map(clean)
|
||||
};
|
||||
|
||||
process.stdout.write(JSON.stringify(obj, null, 2));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a plain-object representation of `test`
|
||||
* free of cyclic properties etc.
|
||||
*
|
||||
* @param {Object} test
|
||||
* @return {Object}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function clean(test) {
|
||||
return {
|
||||
title: test.title
|
||||
, fullTitle: test.fullTitle()
|
||||
, duration: test.duration
|
||||
}
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var Base = require('./base')
|
||||
, cursor = Base.cursor
|
||||
, color = Base.color;
|
||||
|
||||
/**
|
||||
* Expose `Landing`.
|
||||
*/
|
||||
|
||||
exports = module.exports = Landing;
|
||||
|
||||
/**
|
||||
* Airplane color.
|
||||
*/
|
||||
|
||||
Base.colors.plane = 0;
|
||||
|
||||
/**
|
||||
* Airplane crash color.
|
||||
*/
|
||||
|
||||
Base.colors['plane crash'] = 31;
|
||||
|
||||
/**
|
||||
* Runway color.
|
||||
*/
|
||||
|
||||
Base.colors.runway = 90;
|
||||
|
||||
/**
|
||||
* Initialize a new `Landing` reporter.
|
||||
*
|
||||
* @param {Runner} runner
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function Landing(runner) {
|
||||
Base.call(this, runner);
|
||||
|
||||
var self = this
|
||||
, stats = this.stats
|
||||
, width = Base.window.width * .75 | 0
|
||||
, total = runner.total
|
||||
, stream = process.stdout
|
||||
, plane = color('plane', '✈')
|
||||
, crashed = -1
|
||||
, n = 0;
|
||||
|
||||
function runway() {
|
||||
var buf = Array(width).join('-');
|
||||
return ' ' + color('runway', buf);
|
||||
}
|
||||
|
||||
runner.on('start', function(){
|
||||
stream.write('\n ');
|
||||
cursor.hide();
|
||||
});
|
||||
|
||||
runner.on('test end', function(test){
|
||||
// check if the plane crashed
|
||||
var col = -1 == crashed
|
||||
? width * ++n / total | 0
|
||||
: crashed;
|
||||
|
||||
// show the crash
|
||||
if ('failed' == test.state) {
|
||||
plane = color('plane crash', '✈');
|
||||
crashed = col;
|
||||
}
|
||||
|
||||
// render landing strip
|
||||
stream.write('\u001b[4F\n\n');
|
||||
stream.write(runway());
|
||||
stream.write('\n ');
|
||||
stream.write(color('runway', Array(col).join('⋅')));
|
||||
stream.write(plane)
|
||||
stream.write(color('runway', Array(width - col).join('⋅') + '\n'));
|
||||
stream.write(runway());
|
||||
stream.write('\u001b[0m');
|
||||
});
|
||||
|
||||
runner.on('end', function(){
|
||||
cursor.show();
|
||||
console.log();
|
||||
self.epilogue();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Inherit from `Base.prototype`.
|
||||
*/
|
||||
|
||||
Landing.prototype.__proto__ = Base.prototype;
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var Base = require('./base')
|
||||
, cursor = Base.cursor
|
||||
, color = Base.color;
|
||||
|
||||
/**
|
||||
* Expose `List`.
|
||||
*/
|
||||
|
||||
exports = module.exports = List;
|
||||
|
||||
/**
|
||||
* Initialize a new `List` test reporter.
|
||||
*
|
||||
* @param {Runner} runner
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function List(runner) {
|
||||
Base.call(this, runner);
|
||||
|
||||
var self = this
|
||||
, stats = this.stats
|
||||
, n = 0;
|
||||
|
||||
runner.on('start', function(){
|
||||
console.log();
|
||||
});
|
||||
|
||||
runner.on('test', function(test){
|
||||
process.stdout.write(color('pass', ' ' + test.fullTitle() + ': '));
|
||||
});
|
||||
|
||||
runner.on('pending', function(test){
|
||||
var fmt = color('checkmark', ' -')
|
||||
+ color('pending', ' %s');
|
||||
console.log(fmt, test.fullTitle());
|
||||
});
|
||||
|
||||
runner.on('pass', function(test){
|
||||
var fmt = color('checkmark', ' '+Base.symbols.dot)
|
||||
+ color('pass', ' %s: ')
|
||||
+ color(test.speed, '%dms');
|
||||
cursor.CR();
|
||||
console.log(fmt, test.fullTitle(), test.duration);
|
||||
});
|
||||
|
||||
runner.on('fail', function(test, err){
|
||||
cursor.CR();
|
||||
console.log(color('fail', ' %d) %s'), ++n, test.fullTitle());
|
||||
});
|
||||
|
||||
runner.on('end', self.epilogue.bind(self));
|
||||
}
|
||||
|
||||
/**
|
||||
* Inherit from `Base.prototype`.
|
||||
*/
|
||||
|
||||
List.prototype.__proto__ = Base.prototype;
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var Base = require('./base')
|
||||
, utils = require('../utils');
|
||||
|
||||
/**
|
||||
* Expose `Markdown`.
|
||||
*/
|
||||
|
||||
exports = module.exports = Markdown;
|
||||
|
||||
/**
|
||||
* Initialize a new `Markdown` reporter.
|
||||
*
|
||||
* @param {Runner} runner
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function Markdown(runner) {
|
||||
Base.call(this, runner);
|
||||
|
||||
var self = this
|
||||
, stats = this.stats
|
||||
, level = 0
|
||||
, buf = '';
|
||||
|
||||
function title(str) {
|
||||
return Array(level).join('#') + ' ' + str;
|
||||
}
|
||||
|
||||
function indent() {
|
||||
return Array(level).join(' ');
|
||||
}
|
||||
|
||||
function mapTOC(suite, obj) {
|
||||
var ret = obj;
|
||||
obj = obj[suite.title] = obj[suite.title] || { suite: suite };
|
||||
suite.suites.forEach(function(suite){
|
||||
mapTOC(suite, obj);
|
||||
});
|
||||
return ret;
|
||||
}
|
||||
|
||||
function stringifyTOC(obj, level) {
|
||||
++level;
|
||||
var buf = '';
|
||||
var link;
|
||||
for (var key in obj) {
|
||||
if ('suite' == key) continue;
|
||||
if (key) link = ' - [' + key + '](#' + utils.slug(obj[key].suite.fullTitle()) + ')\n';
|
||||
if (key) buf += Array(level).join(' ') + link;
|
||||
buf += stringifyTOC(obj[key], level);
|
||||
}
|
||||
--level;
|
||||
return buf;
|
||||
}
|
||||
|
||||
function generateTOC(suite) {
|
||||
var obj = mapTOC(suite, {});
|
||||
return stringifyTOC(obj, 0);
|
||||
}
|
||||
|
||||
generateTOC(runner.suite);
|
||||
|
||||
runner.on('suite', function(suite){
|
||||
++level;
|
||||
var slug = utils.slug(suite.fullTitle());
|
||||
buf += '<a name="' + slug + '"></a>' + '\n';
|
||||
buf += title(suite.title) + '\n';
|
||||
});
|
||||
|
||||
runner.on('suite end', function(suite){
|
||||
--level;
|
||||
});
|
||||
|
||||
runner.on('pass', function(test){
|
||||
var code = utils.clean(test.fn.toString());
|
||||
buf += test.title + '.\n';
|
||||
buf += '\n```js\n';
|
||||
buf += code + '\n';
|
||||
buf += '```\n\n';
|
||||
});
|
||||
|
||||
runner.on('end', function(){
|
||||
process.stdout.write('# TOC\n');
|
||||
process.stdout.write(generateTOC(runner.suite));
|
||||
process.stdout.write(buf);
|
||||
});
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var Base = require('./base');
|
||||
|
||||
/**
|
||||
* Expose `Min`.
|
||||
*/
|
||||
|
||||
exports = module.exports = Min;
|
||||
|
||||
/**
|
||||
* Initialize a new `Min` minimal test reporter (best used with --watch).
|
||||
*
|
||||
* @param {Runner} runner
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function Min(runner) {
|
||||
Base.call(this, runner);
|
||||
|
||||
runner.on('start', function(){
|
||||
// clear screen
|
||||
process.stdout.write('\u001b[2J');
|
||||
// set cursor position
|
||||
process.stdout.write('\u001b[1;3H');
|
||||
});
|
||||
|
||||
runner.on('end', this.epilogue.bind(this));
|
||||
}
|
||||
|
||||
/**
|
||||
* Inherit from `Base.prototype`.
|
||||
*/
|
||||
|
||||
Min.prototype.__proto__ = Base.prototype;
|
||||
+260
@@ -0,0 +1,260 @@
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var Base = require('./base')
|
||||
, color = Base.color;
|
||||
|
||||
/**
|
||||
* Expose `Dot`.
|
||||
*/
|
||||
|
||||
exports = module.exports = NyanCat;
|
||||
|
||||
/**
|
||||
* Initialize a new `Dot` matrix test reporter.
|
||||
*
|
||||
* @param {Runner} runner
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function NyanCat(runner) {
|
||||
Base.call(this, runner);
|
||||
var self = this
|
||||
, stats = this.stats
|
||||
, width = Base.window.width * .75 | 0
|
||||
, rainbowColors = this.rainbowColors = self.generateColors()
|
||||
, colorIndex = this.colorIndex = 0
|
||||
, numerOfLines = this.numberOfLines = 4
|
||||
, trajectories = this.trajectories = [[], [], [], []]
|
||||
, nyanCatWidth = this.nyanCatWidth = 11
|
||||
, trajectoryWidthMax = this.trajectoryWidthMax = (width - nyanCatWidth)
|
||||
, scoreboardWidth = this.scoreboardWidth = 5
|
||||
, tick = this.tick = 0
|
||||
, n = 0;
|
||||
|
||||
runner.on('start', function(){
|
||||
Base.cursor.hide();
|
||||
self.draw();
|
||||
});
|
||||
|
||||
runner.on('pending', function(test){
|
||||
self.draw();
|
||||
});
|
||||
|
||||
runner.on('pass', function(test){
|
||||
self.draw();
|
||||
});
|
||||
|
||||
runner.on('fail', function(test, err){
|
||||
self.draw();
|
||||
});
|
||||
|
||||
runner.on('end', function(){
|
||||
Base.cursor.show();
|
||||
for (var i = 0; i < self.numberOfLines; i++) write('\n');
|
||||
self.epilogue();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw the nyan cat
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
NyanCat.prototype.draw = function(){
|
||||
this.appendRainbow();
|
||||
this.drawScoreboard();
|
||||
this.drawRainbow();
|
||||
this.drawNyanCat();
|
||||
this.tick = !this.tick;
|
||||
};
|
||||
|
||||
/**
|
||||
* Draw the "scoreboard" showing the number
|
||||
* of passes, failures and pending tests.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
NyanCat.prototype.drawScoreboard = function(){
|
||||
var stats = this.stats;
|
||||
var colors = Base.colors;
|
||||
|
||||
function draw(color, n) {
|
||||
write(' ');
|
||||
write('\u001b[' + color + 'm' + n + '\u001b[0m');
|
||||
write('\n');
|
||||
}
|
||||
|
||||
draw(colors.green, stats.passes);
|
||||
draw(colors.fail, stats.failures);
|
||||
draw(colors.pending, stats.pending);
|
||||
write('\n');
|
||||
|
||||
this.cursorUp(this.numberOfLines);
|
||||
};
|
||||
|
||||
/**
|
||||
* Append the rainbow.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
NyanCat.prototype.appendRainbow = function(){
|
||||
var segment = this.tick ? '_' : '-';
|
||||
var rainbowified = this.rainbowify(segment);
|
||||
|
||||
for (var index = 0; index < this.numberOfLines; index++) {
|
||||
var trajectory = this.trajectories[index];
|
||||
if (trajectory.length >= this.trajectoryWidthMax) trajectory.shift();
|
||||
trajectory.push(rainbowified);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Draw the rainbow.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
NyanCat.prototype.drawRainbow = function(){
|
||||
var self = this;
|
||||
|
||||
this.trajectories.forEach(function(line, index) {
|
||||
write('\u001b[' + self.scoreboardWidth + 'C');
|
||||
write(line.join(''));
|
||||
write('\n');
|
||||
});
|
||||
|
||||
this.cursorUp(this.numberOfLines);
|
||||
};
|
||||
|
||||
/**
|
||||
* Draw the nyan cat
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
NyanCat.prototype.drawNyanCat = function() {
|
||||
var self = this;
|
||||
var startWidth = this.scoreboardWidth + this.trajectories[0].length;
|
||||
var color = '\u001b[' + startWidth + 'C';
|
||||
var padding = '';
|
||||
|
||||
write(color);
|
||||
write('_,------,');
|
||||
write('\n');
|
||||
|
||||
write(color);
|
||||
padding = self.tick ? ' ' : ' ';
|
||||
write('_|' + padding + '/\\_/\\ ');
|
||||
write('\n');
|
||||
|
||||
write(color);
|
||||
padding = self.tick ? '_' : '__';
|
||||
var tail = self.tick ? '~' : '^';
|
||||
var face;
|
||||
write(tail + '|' + padding + this.face() + ' ');
|
||||
write('\n');
|
||||
|
||||
write(color);
|
||||
padding = self.tick ? ' ' : ' ';
|
||||
write(padding + '"" "" ');
|
||||
write('\n');
|
||||
|
||||
this.cursorUp(this.numberOfLines);
|
||||
};
|
||||
|
||||
/**
|
||||
* Draw nyan cat face.
|
||||
*
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
NyanCat.prototype.face = function() {
|
||||
var stats = this.stats;
|
||||
if (stats.failures) {
|
||||
return '( x .x)';
|
||||
} else if (stats.pending) {
|
||||
return '( o .o)';
|
||||
} else if(stats.passes) {
|
||||
return '( ^ .^)';
|
||||
} else {
|
||||
return '( - .-)';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Move cursor up `n`.
|
||||
*
|
||||
* @param {Number} n
|
||||
* @api private
|
||||
*/
|
||||
|
||||
NyanCat.prototype.cursorUp = function(n) {
|
||||
write('\u001b[' + n + 'A');
|
||||
};
|
||||
|
||||
/**
|
||||
* Move cursor down `n`.
|
||||
*
|
||||
* @param {Number} n
|
||||
* @api private
|
||||
*/
|
||||
|
||||
NyanCat.prototype.cursorDown = function(n) {
|
||||
write('\u001b[' + n + 'B');
|
||||
};
|
||||
|
||||
/**
|
||||
* Generate rainbow colors.
|
||||
*
|
||||
* @return {Array}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
NyanCat.prototype.generateColors = function(){
|
||||
var colors = [];
|
||||
|
||||
for (var i = 0; i < (6 * 7); i++) {
|
||||
var pi3 = Math.floor(Math.PI / 3);
|
||||
var n = (i * (1.0 / 6));
|
||||
var r = Math.floor(3 * Math.sin(n) + 3);
|
||||
var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3);
|
||||
var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3);
|
||||
colors.push(36 * r + 6 * g + b + 16);
|
||||
}
|
||||
|
||||
return colors;
|
||||
};
|
||||
|
||||
/**
|
||||
* Apply rainbow to the given `str`.
|
||||
*
|
||||
* @param {String} str
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
NyanCat.prototype.rainbowify = function(str){
|
||||
var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length];
|
||||
this.colorIndex += 1;
|
||||
return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m';
|
||||
};
|
||||
|
||||
/**
|
||||
* Stdout helper.
|
||||
*/
|
||||
|
||||
function write(string) {
|
||||
process.stdout.write(string);
|
||||
}
|
||||
|
||||
/**
|
||||
* Inherit from `Base.prototype`.
|
||||
*/
|
||||
|
||||
NyanCat.prototype.__proto__ = Base.prototype;
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var Base = require('./base')
|
||||
, cursor = Base.cursor
|
||||
, color = Base.color;
|
||||
|
||||
/**
|
||||
* Expose `Progress`.
|
||||
*/
|
||||
|
||||
exports = module.exports = Progress;
|
||||
|
||||
/**
|
||||
* General progress bar color.
|
||||
*/
|
||||
|
||||
Base.colors.progress = 90;
|
||||
|
||||
/**
|
||||
* Initialize a new `Progress` bar test reporter.
|
||||
*
|
||||
* @param {Runner} runner
|
||||
* @param {Object} options
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function Progress(runner, options) {
|
||||
Base.call(this, runner);
|
||||
|
||||
var self = this
|
||||
, options = options || {}
|
||||
, stats = this.stats
|
||||
, width = Base.window.width * .50 | 0
|
||||
, total = runner.total
|
||||
, complete = 0
|
||||
, max = Math.max;
|
||||
|
||||
// default chars
|
||||
options.open = options.open || '[';
|
||||
options.complete = options.complete || '▬';
|
||||
options.incomplete = options.incomplete || Base.symbols.dot;
|
||||
options.close = options.close || ']';
|
||||
options.verbose = false;
|
||||
|
||||
// tests started
|
||||
runner.on('start', function(){
|
||||
console.log();
|
||||
cursor.hide();
|
||||
});
|
||||
|
||||
// tests complete
|
||||
runner.on('test end', function(){
|
||||
complete++;
|
||||
var incomplete = total - complete
|
||||
, percent = complete / total
|
||||
, n = width * percent | 0
|
||||
, i = width - n;
|
||||
|
||||
cursor.CR();
|
||||
process.stdout.write('\u001b[J');
|
||||
process.stdout.write(color('progress', ' ' + options.open));
|
||||
process.stdout.write(Array(n).join(options.complete));
|
||||
process.stdout.write(Array(i).join(options.incomplete));
|
||||
process.stdout.write(color('progress', options.close));
|
||||
if (options.verbose) {
|
||||
process.stdout.write(color('progress', ' ' + complete + ' of ' + total));
|
||||
}
|
||||
});
|
||||
|
||||
// tests are complete, output some stats
|
||||
// and the failures if any
|
||||
runner.on('end', function(){
|
||||
cursor.show();
|
||||
console.log();
|
||||
self.epilogue();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Inherit from `Base.prototype`.
|
||||
*/
|
||||
|
||||
Progress.prototype.__proto__ = Base.prototype;
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var Base = require('./base')
|
||||
, cursor = Base.cursor
|
||||
, color = Base.color;
|
||||
|
||||
/**
|
||||
* Expose `Spec`.
|
||||
*/
|
||||
|
||||
exports = module.exports = Spec;
|
||||
|
||||
/**
|
||||
* Initialize a new `Spec` test reporter.
|
||||
*
|
||||
* @param {Runner} runner
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function Spec(runner) {
|
||||
Base.call(this, runner);
|
||||
|
||||
var self = this
|
||||
, stats = this.stats
|
||||
, indents = 0
|
||||
, n = 0;
|
||||
|
||||
function indent() {
|
||||
return Array(indents).join(' ')
|
||||
}
|
||||
|
||||
runner.on('start', function(){
|
||||
console.log();
|
||||
});
|
||||
|
||||
runner.on('suite', function(suite){
|
||||
++indents;
|
||||
console.log(color('suite', '%s%s'), indent(), suite.title);
|
||||
});
|
||||
|
||||
runner.on('suite end', function(suite){
|
||||
--indents;
|
||||
if (1 == indents) console.log();
|
||||
});
|
||||
|
||||
runner.on('pending', function(test){
|
||||
var fmt = indent() + color('pending', ' - %s');
|
||||
console.log(fmt, test.title);
|
||||
});
|
||||
|
||||
runner.on('pass', function(test){
|
||||
if ('fast' == test.speed) {
|
||||
var fmt = indent()
|
||||
+ color('checkmark', ' ' + Base.symbols.ok)
|
||||
+ color('pass', ' %s ');
|
||||
cursor.CR();
|
||||
console.log(fmt, test.title);
|
||||
} else {
|
||||
var fmt = indent()
|
||||
+ color('checkmark', ' ' + Base.symbols.ok)
|
||||
+ color('pass', ' %s ')
|
||||
+ color(test.speed, '(%dms)');
|
||||
cursor.CR();
|
||||
console.log(fmt, test.title, test.duration);
|
||||
}
|
||||
});
|
||||
|
||||
runner.on('fail', function(test, err){
|
||||
cursor.CR();
|
||||
console.log(indent() + color('fail', ' %d) %s'), ++n, test.title);
|
||||
});
|
||||
|
||||
runner.on('end', self.epilogue.bind(self));
|
||||
}
|
||||
|
||||
/**
|
||||
* Inherit from `Base.prototype`.
|
||||
*/
|
||||
|
||||
Spec.prototype.__proto__ = Base.prototype;
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var Base = require('./base')
|
||||
, cursor = Base.cursor
|
||||
, color = Base.color;
|
||||
|
||||
/**
|
||||
* Expose `TAP`.
|
||||
*/
|
||||
|
||||
exports = module.exports = TAP;
|
||||
|
||||
/**
|
||||
* Initialize a new `TAP` reporter.
|
||||
*
|
||||
* @param {Runner} runner
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function TAP(runner) {
|
||||
Base.call(this, runner);
|
||||
|
||||
var self = this
|
||||
, stats = this.stats
|
||||
, n = 1
|
||||
, passes = 0
|
||||
, failures = 0;
|
||||
|
||||
runner.on('start', function(){
|
||||
var total = runner.grepTotal(runner.suite);
|
||||
console.log('%d..%d', 1, total);
|
||||
});
|
||||
|
||||
runner.on('test end', function(){
|
||||
++n;
|
||||
});
|
||||
|
||||
runner.on('pending', function(test){
|
||||
console.log('ok %d %s # SKIP -', n, title(test));
|
||||
});
|
||||
|
||||
runner.on('pass', function(test){
|
||||
passes++;
|
||||
console.log('ok %d %s', n, title(test));
|
||||
});
|
||||
|
||||
runner.on('fail', function(test, err){
|
||||
failures++;
|
||||
console.log('not ok %d %s', n, title(test));
|
||||
if (err.stack) console.log(err.stack.replace(/^/gm, ' '));
|
||||
});
|
||||
|
||||
runner.on('end', function(){
|
||||
console.log('# tests ' + (passes + failures));
|
||||
console.log('# pass ' + passes);
|
||||
console.log('# fail ' + failures);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a TAP-safe title of `test`
|
||||
*
|
||||
* @param {Object} test
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function title(test) {
|
||||
return test.fullTitle().replace(/#/g, '');
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
!!! 5
|
||||
html
|
||||
head
|
||||
title Coverage
|
||||
include script.html
|
||||
include style.html
|
||||
body
|
||||
#coverage
|
||||
h1#overview Coverage
|
||||
include menu
|
||||
|
||||
#stats(class=coverageClass(cov.coverage))
|
||||
.percentage #{cov.coverage | 0}%
|
||||
.sloc= cov.sloc
|
||||
.hits= cov.hits
|
||||
.misses= cov.misses
|
||||
|
||||
#files
|
||||
for file in cov.files
|
||||
.file
|
||||
h2(id=file.filename)= file.filename
|
||||
#stats(class=coverageClass(file.coverage))
|
||||
.percentage #{file.coverage | 0}%
|
||||
.sloc= file.sloc
|
||||
.hits= file.hits
|
||||
.misses= file.misses
|
||||
|
||||
table#source
|
||||
thead
|
||||
tr
|
||||
th Line
|
||||
th Hits
|
||||
th Source
|
||||
tbody
|
||||
for line, number in file.source
|
||||
if line.coverage > 0
|
||||
tr.hit
|
||||
td.line= number
|
||||
td.hits= line.coverage
|
||||
td.source= line.source
|
||||
else if 0 === line.coverage
|
||||
tr.miss
|
||||
td.line= number
|
||||
td.hits 0
|
||||
td.source= line.source
|
||||
else
|
||||
tr
|
||||
td.line= number
|
||||
td.hits
|
||||
td.source= line.source || ' '
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
#menu
|
||||
li
|
||||
a(href='#overview') overview
|
||||
for file in cov.files
|
||||
li
|
||||
span.cov(class=coverageClass(file.coverage)) #{file.coverage | 0}
|
||||
a(href='##{file.filename}')
|
||||
segments = file.filename.split('/')
|
||||
basename = segments.pop()
|
||||
if segments.length
|
||||
span.dirname= segments.join('/') + '/'
|
||||
span.basename= basename
|
||||
a#logo(href='http://visionmedia.github.io/mocha/') m
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
<script>
|
||||
|
||||
headings = [];
|
||||
|
||||
onload = function(){
|
||||
headings = document.querySelectorAll('h2');
|
||||
};
|
||||
|
||||
onscroll = function(e){
|
||||
var heading = find(window.scrollY);
|
||||
if (!heading) return;
|
||||
var links = document.querySelectorAll('#menu a')
|
||||
, link;
|
||||
|
||||
for (var i = 0, len = links.length; i < len; ++i) {
|
||||
link = links[i];
|
||||
link.className = link.getAttribute('href') == '#' + heading.id
|
||||
? 'active'
|
||||
: '';
|
||||
}
|
||||
};
|
||||
|
||||
function find(y) {
|
||||
var i = headings.length
|
||||
, heading;
|
||||
|
||||
while (i--) {
|
||||
heading = headings[i];
|
||||
if (y >= heading.offsetTop) {
|
||||
return heading;
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
+320
@@ -0,0 +1,320 @@
|
||||
<style>
|
||||
|
||||
body {
|
||||
font: 14px/1.6 "Helvetica Neue", Helvetica, Arial, sans-serif;
|
||||
margin: 0;
|
||||
color: #2C2C2C;
|
||||
border-top: 2px solid #ddd;
|
||||
}
|
||||
|
||||
#coverage {
|
||||
padding: 60px;
|
||||
}
|
||||
|
||||
h1 a {
|
||||
color: inherit;
|
||||
font-weight: inherit;
|
||||
}
|
||||
|
||||
h1 a:hover {
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.onload h1 {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
h2 {
|
||||
width: 80%;
|
||||
margin-top: 80px;
|
||||
margin-bottom: 0;
|
||||
font-weight: 100;
|
||||
letter-spacing: 1px;
|
||||
border-bottom: 1px solid #eee;
|
||||
}
|
||||
|
||||
a {
|
||||
color: #8A6343;
|
||||
font-weight: bold;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
ul {
|
||||
margin-top: 20px;
|
||||
padding: 0 15px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
ul li {
|
||||
float: left;
|
||||
width: 40%;
|
||||
margin-top: 5px;
|
||||
margin-right: 60px;
|
||||
list-style: none;
|
||||
border-bottom: 1px solid #eee;
|
||||
padding: 5px 0;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
ul::after {
|
||||
content: '.';
|
||||
height: 0;
|
||||
display: block;
|
||||
visibility: hidden;
|
||||
clear: both;
|
||||
}
|
||||
|
||||
code {
|
||||
font: 12px monaco, monospace;
|
||||
}
|
||||
|
||||
pre {
|
||||
margin: 30px;
|
||||
padding: 30px;
|
||||
border: 1px solid #eee;
|
||||
border-bottom-color: #ddd;
|
||||
-webkit-border-radius: 2px;
|
||||
-moz-border-radius: 2px;
|
||||
border-radius: 2px;
|
||||
-webkit-box-shadow: inset 0 0 10px #eee;
|
||||
-moz-box-shadow: inset 0 0 10px #eee;
|
||||
box-shadow: inset 0 0 10px #eee;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
img {
|
||||
margin: 30px;
|
||||
padding: 1px;
|
||||
-webkit-border-radius: 3px;
|
||||
-moz-border-radius: 3px;
|
||||
border-radius: 3px;
|
||||
-webkit-box-shadow: 0 3px 10px #dedede, 0 1px 5px #888;
|
||||
-moz-box-shadow: 0 3px 10px #dedede, 0 1px 5px #888;
|
||||
box-shadow: 0 3px 10px #dedede, 0 1px 5px #888;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
footer {
|
||||
background: #eee;
|
||||
width: 100%;
|
||||
padding: 50px 0;
|
||||
text-align: right;
|
||||
border-top: 1px solid #ddd;
|
||||
}
|
||||
|
||||
footer span {
|
||||
display: block;
|
||||
margin-right: 30px;
|
||||
color: #888;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
#menu {
|
||||
position: fixed;
|
||||
font-size: 12px;
|
||||
overflow-y: auto;
|
||||
top: 0;
|
||||
right: 0;
|
||||
margin: 0;
|
||||
height: 100%;
|
||||
padding: 15px 0;
|
||||
text-align: right;
|
||||
border-left: 1px solid #eee;
|
||||
-moz-box-shadow: 0 0 2px #888
|
||||
, inset 5px 0 20px rgba(0,0,0,.5)
|
||||
, inset 5px 0 3px rgba(0,0,0,.3);
|
||||
-webkit-box-shadow: 0 0 2px #888
|
||||
, inset 5px 0 20px rgba(0,0,0,.5)
|
||||
, inset 5px 0 3px rgba(0,0,0,.3);
|
||||
box-shadow: 0 0 2px #888
|
||||
, inset 5px 0 20px rgba(0,0,0,.5)
|
||||
, inset 5px 0 3px rgba(0,0,0,.3);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGYAAABmCAMAAAAOARRQAAABelBMVEUjJSU6OzshIyM5OjoqKy02NjgsLS01NTYjJCUzNTUgISMlJSc0NTUvMDA6PDwlJyg1NjYoKis2NjYrLS02ODkpKyw0NDYrLC04ODovLzA4Ojo0NDUtLy86OjwjIyU4OTosLS82ODgtLS8hIyQvMTEnKCooKSsrKy0qLCwkJSUnKCkrLCwpKiwwMjIxMzMqLC0tLS0pKissLC00NTYwMDIwMTQpKysoKSovMDEtLzA2OTkxMzUrKywvLy8qKyszNTY5OzsqKiw6OjswMDExNDUoKiozNDUvMDIyNDY1Njg2Njk5OTozMzU0NjY4ODkiIyUiIyQ4OTkuMDEmKCowMjQwMTErLS4qKywwMTMhIiMpKiopKy0tLjAkJScxNDQvLzExNDYyNDQmKCk5OTslJig5OjskJSYxMzQrLS8gISIwMTIoKCk1NTUlJSUnJygwMDA4ODgiIiMhISI8PDw6Ojo5OTkpKSojIyQ7OzsyMjIpKSssLCw6Ozw1NjlrfLakAAAg2UlEQVR42jR6i3ea6rYvPgANIAhVXh8WvkQlioUiFlFcBtAmoiRNdzxqu9p0J7vrdK29zuPeex77nnvO/35n1r1ndHRktI0jTOacv/l7lCBK5UqVpOha/YxmWK7BC4TQFKVXrbYsnimqxuuMVlOQ0XltWjUdCwRJ1M+tC1KudOs9q6+da2adUewG0SC0SwELfHtgDds93VEuydEbl3QMWeNoYkR7b/0x1ZRobGI3mLwzAhePqTAwhg6aogjNsGy7/jwQ4rkdqe7CWLxF8k9LfMVFyRS7VJqtkrW8Vt/bkR8FZJao16ipknbC3Yw2lM7laO6HBEOadEZ2tpf65c4v8e3u7FyU6qbiNNyCuzXZ6pawgnwgmrpTT/Q7w2EZmiIJ0dzWDI7mhQ80IfRnMu2kzA5r5r1pIFoia+/d93HRYp1GV8TbrkWoU/+jdI0Ff6yGwTjT1Hn8J+8m1rKpGiYPuNiHnMtNMIv+zpsk84MYTNW1/+DpwXLvckdOCMYowVNPREe0QlM8xRHXXFhcNDzupwsSmb5pH+0t0RP2Qk+QtI7F1Qm6JRC6ZPBtPq/dq/kH+jxtCljn9TIpW6rQIgmSVyj6lPICIw4N/taka41PFUInth0je9+jO6Kt1G4/a7V2LEgG02B0pHVuCZrgltSKMuIl5SyufUv9mYuQi+mFgzbBEtFo2g+Dh4sSTrLNu8JPh00sQydpb00tqXBvqRN7Q7kqzcnIxCGnvZt/WmJacoOEO6Dcn8Qre03pOCSQxbMOXUuDNx9SxuLz4W1I18gvjViQ67zV0rxdWL8Te/TQkuo8STS41DR48W7L6YP2uWIqiUV8rd6Gbf/rnegKZeG8TpAM6afhGze9JAOxbLjsnUXEbrZ9vLYd7MT32cPF5mKKxmjy7huaoD9n62GOxni3iIJwv0IzZAZjdZkUtolCNLVfYZNaquFjGszVVf+J0vrz4CawoKdHnOzb0NMH7CDBOybfYNJ4rfeMyFNjkFYVTzMFs87rnPGXLUOeNKRVc0LnU7/UIgelzsy3CMuth0YfvnY0wsD3vODUL3eJcKqHQpm8yM3XZQWJxO6Un9iYloyyLpOwN2obHy6W6gbpcb44XmyC+mg+itAcaprGcrwZCqMj/GmtKn0zPvpTz/Cv1dw21XwP3cRupg3H3MF/S71eTKj1YrdwKdc2Mw0fRmb2sFf8lW3aU6JbIZSEPqvXvjM7G/aApyXlXeqKfMq0g/Su3rUGJPSPrtGElgknrZM3xUXqsAP6zMCNVn5u8aJnSNpJv2uru7t2jfRziW2+GuhqfldUNbPk71olwo+46ePUo1U3WKk/e5YK07F/wGRgcpODmQnIlVeHCWBE4puBi2jq28UKpqiN1/4UOrGz59TNYrrQHtd+11sG40BGD+pXdelNqGOg4NXe8W4eacJV/NS9/2Umtym6WQqveqR9xdCMElpxnbkalM4Vf9uaEcWZaKdyibEIjWKxJZPN95niCL3GiaXyssIrHxoLkqkzLCXULN46/f2h3tQJgyip+Tk9EAjJ9aJshq7t8X45aowSKspMSvPf7r9R8yxNptIaHS5ozuEm6luPDApugyNP8OaqiQ4BjaequXA54SLC83eHIY2r+CZp4409Xqw8Aa2oI7XkCrQi+in0w5AqF/kLNrcUz+qkl/lAobY1jSnx5OJNhyXIz3qfNFlXc0TKaglNwdWkWYt9QQ1Kr6W8zue21iNrdJk+N5oCr2O9nEtWKC7IS5J/zdDEYrmnAYfg6agCy+qcgz7ZofeDc4PbUWSvkshWuAc7OjiUyLkj+RAtdlwXJcjxdpkTTHDhK8lBCi8+JtvDVL1W6elmOM++YS0LuSlaP1oUvAeiW3cFnvTr8EbTz1tsSMYdGeZe40sRWu5uAfj7q+ZoKv2FNQ0p5XY1lmlcigHZqTPpabufEVrNuNPi165w3uCVQJHyJqmSJ7ZHnguqwtCmwViIJijj04ba2JNYtB+yORf5gg1/9t9iw4vUpeqiunSAbf+IBdj/b+iG2qrHvuNP0Vd/+ThVZT/lrvHYjjgDbbyxaqgHNM2uhxa1GW3UedZYhMMwM4mQhltouK+IV4NdbIQNM+8Yv311RZk9kT4tiYR4LkyFcuPpdcjuhUuFqBAWRZa11lcZ3gEBlXywsNhrt+plISZP5DlsV9l4EgY6J3yZPTUcMrgaWAT3oI79eSbGEbcJpr6BD8kyDiVt+G0/hXosQN4NFXKlfWIfsIs0BHODVok1/IGnKFHJYIquh8Xo+2+bkQNTGgWmN/fZ0Y33LSj6lr1GyV7mWIKg7ZTRZPGuhF/zjRNcQ1UPtSYgnWQxSs0yrVhwNDcdGMNSNe2JT3WuzbAM3HykyAajS3Uphf6STKEqxLas9EnmnhA/lyj9Uj+JoY7SVgVmGLl46Rm2u98sbkap2lzAdKBG4r6LgulQOSSjQv1GWdQ0jtDUK/mAaqM1Uqjpu4k3Rvfvxv7YTxLSK+wN3E5jVIzmF23uZ7hiH/sVP49D7tvoKp4S8b1LuvRlivVB/algbhcFITYVXvDpLzpDfplR2uD5V4XJFxpjmIpLc9Y5sB2TpBRix7Bme6GZIq+06v3XzNeTcA4obQIKxrnT4C2JpOqD92dbmSX8MGazly5EsZVMvSU1f4RZwyu8iQXbVdeLlZrjuTT1jrY1uk5c7iZ7RsvhhluqAkq4JpVQAg7RJFtSu+xgJ8Pv6O1j5DkLxT8mkbfyRW5DrQmG7hiDIjCgBsADbjuof6YHLGeV6a5Q1Smx9joUXPpdaaDx97A/Wq00oJkdR7ZYuQRfS533JtxO1erduqWOYIt3wh0wpbLuCNIYkwxbswbikCUu2CDCS+Q+7rgVtfRcm+SOcdKPRlZ/rE7wNVUEE39KTS5uvUKN1PUnkloPkyzhyGQ8qkouEjJ3H/VXdqG6asSRiw3ecMlBvDDt8dDhBHXMwZ2Cajzjr7/76T+IavqPYvz6r7//E/3X3+N//h/0QozbjPgPiir69P/8X3/9F/yv8b/827/++98WItPu5/Hvwd8YPf5bp/2/lX/T/+Of/0MJ/lYTa+L/Ef+d9vN/3/2T6P/+jyTzu/evf6U7vxN7B6pJkRtAF6jUr8I+P8RsP/ptGhfqFk+pQ/DgAy6NJtRYJdXmp4gK7WLqLKJ+MaKhGjOojvL+SnIWrkpy0SLHDe4QuyNzaEA15mLMCcmE8Em+4HdOihW4/ZWuppJEmzeAwcDtv7MuLc9y2V5atvxXNe3S4DUMt5/Qy2LM9kSYKiVWBuKlfp4nxTntpuW03JbIlkiRvBXmT23g1I2OYe6IizUHPIq6zm6mbfsbteKmi/sg9J+ocQBMctGFO7iljo8TPN+z3jxw4do+ZwfqoR9dkNTKHyM305GpTkfhcHexVkPVGEbUOjuo9f0UMPHBFlGEx0SLvJvVRKTwW7PSew5oPme+E42+frJa9cGt2njS3dK5kIif2eYbhuSEQXEqMVfUjhGIuin0G0/W5ezJyJQy3SpMLai4M0JUWb5u1k9tny5bd1pPwYBpQuDCXZl62xg4CdVEAtflXHs6JKmP/pH6mOl796Lgopj0o8d5kKh00hxG3OSdEE/QBo9Hgr8JJqAeLDwJohG5j/DGh61Rc/+tf22/8kEnxHNCEjo0ElvvGfESZkqmz2BDcKV1H1buSkhkdg7p1IMGs2s17nYjpblrWuE2K9WEO/hcRp5e9oOF/QBmOaDtgil+oaU6szPrdwW65fOB0KUTsVUn7LFU7J8e6cxJIl9+FHw5MQMzuQJ+4oxMH3iW/5GK+hWuG0T+gTLs+fAjdtUd58TmIUq04EeyRCYCjkldow234aIgR5bqwrtZosZ+6YEqAmDqatJ9lWasz4IquKALPtd92hGI3Z2BdzzZue+REl1Om4DIWD+RrtUTOJLI+S0jHowXXdAxsGLSd40zYNuEUlOGhrwL6c7tcOtUOvpJCP7QBQS19H+GvZn05ewjlVLz+IGKoC9TyfQjLMBNmXCuqqtTdOSukZW48B0HqgSTCBrBnlFvF4CG2Su7yFzqmJFURK3UmTT3ru050r0ptUpMilYnBJWfl2Bv6kPlUuE1kxxpdzui9AubsR2N2boVSu81OulAwBqoSr1LZ0LLYOomyZHmjqnXlP72s8LnDouEJjtodBvdHaG1jMySYO7crWd90MpCRyCG14vb5IE7Arupw/y/RcCm/Tm3zK6zYj8PYNaGldiUfkB/LHWcmf2lVM+mwyU27a0qq2tscrQ/vzBjN26DnntIrOyGizzXK35yKQdYnUABkyN4saz3WD/viF+eCcsXnIajdWYJWaYHRstIis9CS+tqnFGmz2j5uzfr3Z4prqgK4XOT/PyftvjZqIm8lhkfxJ7Ol3CJF1piYBGAG8wtAkLine truncated
|
||||
}
|
||||
|
||||
#menu::after {
|
||||
display: block;
|
||||
content: '';
|
||||
padding-top: 80px;
|
||||
}
|
||||
|
||||
#logo {
|
||||
position: fixed;
|
||||
bottom: 10px;
|
||||
right: 10px;
|
||||
background: rgba(255,255,255,.1);
|
||||
font-size: 11px;
|
||||
display: block;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
line-height: 20px;
|
||||
text-align: center;
|
||||
-webkit-border-radius: 20px;
|
||||
-moz-border-radius: 20px;
|
||||
border-radius: 20px;
|
||||
-webkit-box-shadow: 0 0 3px rgba(0,0,0,.2);
|
||||
-moz-box-shadow: 0 0 3px rgba(0,0,0,.2);
|
||||
box-shadow: 0 0 3px rgba(0,0,0,.2);
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
#menu li a {
|
||||
display: block;
|
||||
color: white;
|
||||
padding: 0 35px 0 25px;
|
||||
-webkit-transition: background 300ms;
|
||||
-moz-transition: background 300ms;
|
||||
}
|
||||
|
||||
#menu li {
|
||||
position: relative;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
#menu a:hover,
|
||||
#menu a.active {
|
||||
text-decoration: none;
|
||||
background: rgba(255,255,255,.1);
|
||||
}
|
||||
|
||||
#menu li:hover .cov {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
#menu li .dirname {
|
||||
opacity: .60;
|
||||
padding-right: 2px;
|
||||
}
|
||||
|
||||
#menu li .basename {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
#menu .cov {
|
||||
background: rgba(0,0,0,.4);
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 8px;
|
||||
font-size: 9px;
|
||||
opacity: .6;
|
||||
text-align: left;
|
||||
width: 17px;
|
||||
-webkit-border-radius: 10px;
|
||||
-moz-border-radius: 10px;
|
||||
border-radius: 10px;
|
||||
padding: 2px 3px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
#stats:nth-child(2n) {
|
||||
display: inline-block;
|
||||
margin-top: 15px;
|
||||
border: 1px solid #eee;
|
||||
padding: 10px;
|
||||
-webkit-box-shadow: inset 0 0 2px #eee;
|
||||
-moz-box-shadow: inset 0 0 2px #eee;
|
||||
box-shadow: inset 0 0 2px #eee;
|
||||
-webkit-border-radius: 5px;
|
||||
-moz-border-radius: 5px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
#stats div {
|
||||
float: left;
|
||||
padding: 0 5px;
|
||||
}
|
||||
|
||||
#stats::after {
|
||||
display: block;
|
||||
content: '';
|
||||
clear: both;
|
||||
}
|
||||
|
||||
#stats .sloc::after {
|
||||
content: ' SLOC';
|
||||
color: #b6b6b6;
|
||||
}
|
||||
|
||||
#stats .percentage::after {
|
||||
content: ' coverage';
|
||||
color: #b6b6b6;
|
||||
}
|
||||
|
||||
#stats .hits,
|
||||
#stats .misses {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.high {
|
||||
color: #00d4b4;
|
||||
}
|
||||
.medium {
|
||||
color: #e87d0d;
|
||||
}
|
||||
.low {
|
||||
color: #d4081a;
|
||||
}
|
||||
.terrible {
|
||||
color: #d4081a;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 80%;
|
||||
margin-top: 10px;
|
||||
border-collapse: collapse;
|
||||
border: 1px solid #cbcbcb;
|
||||
color: #363636;
|
||||
-webkit-border-radius: 3px;
|
||||
-moz-border-radius: 3px;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
table thead {
|
||||
display: none;
|
||||
}
|
||||
|
||||
table td.line,
|
||||
table td.hits {
|
||||
width: 20px;
|
||||
background: #eaeaea;
|
||||
text-align: center;
|
||||
font-size: 11px;
|
||||
padding: 0 10px;
|
||||
color: #949494;
|
||||
}
|
||||
|
||||
table td.hits {
|
||||
width: 10px;
|
||||
padding: 2px 5px;
|
||||
color: rgba(0,0,0,.2);
|
||||
background: #f0f0f0;
|
||||
}
|
||||
|
||||
tr.miss td.line,
|
||||
tr.miss td.hits {
|
||||
background: #e6c3c7;
|
||||
}
|
||||
|
||||
tr.miss td {
|
||||
background: #f8d5d8;
|
||||
}
|
||||
|
||||
td.source {
|
||||
padding-left: 15px;
|
||||
line-height: 15px;
|
||||
white-space: pre;
|
||||
font: 12px monaco, monospace;
|
||||
}
|
||||
|
||||
code .comment { color: #ddd }
|
||||
code .init { color: #2F6FAD }
|
||||
code .string { color: #5890AD }
|
||||
code .keyword { color: #8A6343 }
|
||||
code .number { color: #2F6FAD }
|
||||
</style>
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var Base = require('./base')
|
||||
, utils = require('../utils')
|
||||
, escape = utils.escape;
|
||||
|
||||
/**
|
||||
* Save timer references to avoid Sinon interfering (see GH-237).
|
||||
*/
|
||||
|
||||
var Date = global.Date
|
||||
, setTimeout = global.setTimeout
|
||||
, setInterval = global.setInterval
|
||||
, clearTimeout = global.clearTimeout
|
||||
, clearInterval = global.clearInterval;
|
||||
|
||||
/**
|
||||
* Expose `XUnit`.
|
||||
*/
|
||||
|
||||
exports = module.exports = XUnit;
|
||||
|
||||
/**
|
||||
* Initialize a new `XUnit` reporter.
|
||||
*
|
||||
* @param {Runner} runner
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function XUnit(runner) {
|
||||
Base.call(this, runner);
|
||||
var stats = this.stats
|
||||
, tests = []
|
||||
, self = this;
|
||||
|
||||
runner.on('pending', function(test){
|
||||
tests.push(test);
|
||||
});
|
||||
|
||||
runner.on('pass', function(test){
|
||||
tests.push(test);
|
||||
});
|
||||
|
||||
runner.on('fail', function(test){
|
||||
tests.push(test);
|
||||
});
|
||||
|
||||
runner.on('end', function(){
|
||||
console.log(tag('testsuite', {
|
||||
name: 'Mocha Tests'
|
||||
, tests: stats.tests
|
||||
, failures: stats.failures
|
||||
, errors: stats.failures
|
||||
, skipped: stats.tests - stats.failures - stats.passes
|
||||
, timestamp: (new Date).toUTCString()
|
||||
, time: (stats.duration / 1000) || 0
|
||||
}, false));
|
||||
|
||||
tests.forEach(test);
|
||||
console.log('</testsuite>');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Inherit from `Base.prototype`.
|
||||
*/
|
||||
|
||||
XUnit.prototype.__proto__ = Base.prototype;
|
||||
|
||||
/**
|
||||
* Output tag for the given `test.`
|
||||
*/
|
||||
|
||||
function test(test) {
|
||||
var attrs = {
|
||||
classname: test.parent.fullTitle()
|
||||
, name: test.title
|
||||
, time: (test.duration / 1000) || 0
|
||||
};
|
||||
|
||||
if ('failed' == test.state) {
|
||||
var err = test.err;
|
||||
attrs.message = escape(err.message);
|
||||
console.log(tag('testcase', attrs, false, tag('failure', attrs, false, cdata(err.stack))));
|
||||
} else if (test.pending) {
|
||||
console.log(tag('testcase', attrs, false, tag('skipped', {}, true)));
|
||||
} else {
|
||||
console.log(tag('testcase', attrs, true) );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* HTML tag helper.
|
||||
*/
|
||||
|
||||
function tag(name, attrs, close, content) {
|
||||
var end = close ? '/>' : '>'
|
||||
, pairs = []
|
||||
, tag;
|
||||
|
||||
for (var key in attrs) {
|
||||
pairs.push(key + '="' + escape(attrs[key]) + '"');
|
||||
}
|
||||
|
||||
tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end;
|
||||
if (content) tag += content + '</' + name + end;
|
||||
return tag;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return cdata escaped CDATA `str`.
|
||||
*/
|
||||
|
||||
function cdata(str) {
|
||||
return '<![CDATA[' + escape(str) + ']]>';
|
||||
}
|
||||
+227
@@ -0,0 +1,227 @@
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var EventEmitter = require('events').EventEmitter
|
||||
, debug = require('debug')('mocha:runnable')
|
||||
, milliseconds = require('./ms');
|
||||
|
||||
/**
|
||||
* Save timer references to avoid Sinon interfering (see GH-237).
|
||||
*/
|
||||
|
||||
var Date = global.Date
|
||||
, setTimeout = global.setTimeout
|
||||
, setInterval = global.setInterval
|
||||
, clearTimeout = global.clearTimeout
|
||||
, clearInterval = global.clearInterval;
|
||||
|
||||
/**
|
||||
* Object#toString().
|
||||
*/
|
||||
|
||||
var toString = Object.prototype.toString;
|
||||
|
||||
/**
|
||||
* Expose `Runnable`.
|
||||
*/
|
||||
|
||||
module.exports = Runnable;
|
||||
|
||||
/**
|
||||
* Initialize a new `Runnable` with the given `title` and callback `fn`.
|
||||
*
|
||||
* @param {String} title
|
||||
* @param {Function} fn
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function Runnable(title, fn) {
|
||||
this.title = title;
|
||||
this.fn = fn;
|
||||
this.async = fn && fn.length;
|
||||
this.sync = ! this.async;
|
||||
this._timeout = 2000;
|
||||
this._slow = 75;
|
||||
this.timedOut = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inherit from `EventEmitter.prototype`.
|
||||
*/
|
||||
|
||||
Runnable.prototype.__proto__ = EventEmitter.prototype;
|
||||
|
||||
/**
|
||||
* Set & get timeout `ms`.
|
||||
*
|
||||
* @param {Number|String} ms
|
||||
* @return {Runnable|Number} ms or self
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Runnable.prototype.timeout = function(ms){
|
||||
if (0 == arguments.length) return this._timeout;
|
||||
if ('string' == typeof ms) ms = milliseconds(ms);
|
||||
debug('timeout %d', ms);
|
||||
this._timeout = ms;
|
||||
if (this.timer) this.resetTimeout();
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Set & get slow `ms`.
|
||||
*
|
||||
* @param {Number|String} ms
|
||||
* @return {Runnable|Number} ms or self
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Runnable.prototype.slow = function(ms){
|
||||
if (0 === arguments.length) return this._slow;
|
||||
if ('string' == typeof ms) ms = milliseconds(ms);
|
||||
debug('timeout %d', ms);
|
||||
this._slow = ms;
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the full title generated by recursively
|
||||
* concatenating the parent's full title.
|
||||
*
|
||||
* @return {String}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Runnable.prototype.fullTitle = function(){
|
||||
return this.parent.fullTitle() + ' ' + this.title;
|
||||
};
|
||||
|
||||
/**
|
||||
* Clear the timeout.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Runnable.prototype.clearTimeout = function(){
|
||||
clearTimeout(this.timer);
|
||||
};
|
||||
|
||||
/**
|
||||
* Inspect the runnable void of private properties.
|
||||
*
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Runnable.prototype.inspect = function(){
|
||||
return JSON.stringify(this, function(key, val){
|
||||
if ('_' == key[0]) return;
|
||||
if ('parent' == key) return '#<Suite>';
|
||||
if ('ctx' == key) return '#<Context>';
|
||||
return val;
|
||||
}, 2);
|
||||
};
|
||||
|
||||
/**
|
||||
* Reset the timeout.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Runnable.prototype.resetTimeout = function(){
|
||||
var self = this;
|
||||
var ms = this.timeout() || 1e9;
|
||||
|
||||
this.clearTimeout();
|
||||
this.timer = setTimeout(function(){
|
||||
self.callback(new Error('timeout of ' + ms + 'ms exceeded'));
|
||||
self.timedOut = true;
|
||||
}, ms);
|
||||
};
|
||||
|
||||
/**
|
||||
* Whitelist these globals for this test run
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
Runnable.prototype.globals = function(arr){
|
||||
var self = this;
|
||||
this._allowedGlobals = arr;
|
||||
};
|
||||
|
||||
/**
|
||||
* Run the test and invoke `fn(err)`.
|
||||
*
|
||||
* @param {Function} fn
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Runnable.prototype.run = function(fn){
|
||||
var self = this
|
||||
, ms = this.timeout()
|
||||
, start = new Date
|
||||
, ctx = this.ctx
|
||||
, finished
|
||||
, emitted;
|
||||
|
||||
if (ctx) ctx.runnable(this);
|
||||
|
||||
// timeout
|
||||
if (this.async) {
|
||||
if (ms) {
|
||||
this.timer = setTimeout(function(){
|
||||
done(new Error('timeout of ' + ms + 'ms exceeded'));
|
||||
self.timedOut = true;
|
||||
}, ms);
|
||||
}
|
||||
}
|
||||
|
||||
// called multiple times
|
||||
function multiple(err) {
|
||||
if (emitted) return;
|
||||
emitted = true;
|
||||
self.emit('error', err || new Error('done() called multiple times'));
|
||||
}
|
||||
|
||||
// finished
|
||||
function done(err) {
|
||||
if (self.timedOut) return;
|
||||
if (finished) return multiple(err);
|
||||
self.clearTimeout();
|
||||
self.duration = new Date - start;
|
||||
finished = true;
|
||||
fn(err);
|
||||
}
|
||||
|
||||
// for .resetTimeout()
|
||||
this.callback = done;
|
||||
|
||||
// async
|
||||
if (this.async) {
|
||||
try {
|
||||
this.fn.call(ctx, function(err){
|
||||
if (err instanceof Error || toString.call(err) === "[object Error]") return done(err);
|
||||
if (null != err) return done(new Error('done() invoked with non-Error: ' + err));
|
||||
done();
|
||||
});
|
||||
} catch (err) {
|
||||
done(err);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.asyncOnly) {
|
||||
return done(new Error('--async-only option in use without declaring `done()`'));
|
||||
}
|
||||
|
||||
// sync
|
||||
try {
|
||||
if (!this.pending) this.fn.call(ctx);
|
||||
this.duration = new Date - start;
|
||||
fn();
|
||||
} catch (err) {
|
||||
fn(err);
|
||||
}
|
||||
};
|
||||
+661
@@ -0,0 +1,661 @@
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var EventEmitter = require('events').EventEmitter
|
||||
, debug = require('debug')('mocha:runner')
|
||||
, Test = require('./test')
|
||||
, utils = require('./utils')
|
||||
, filter = utils.filter
|
||||
, keys = utils.keys;
|
||||
|
||||
/**
|
||||
* Non-enumerable globals.
|
||||
*/
|
||||
|
||||
var globals = [
|
||||
'setTimeout',
|
||||
'clearTimeout',
|
||||
'setInterval',
|
||||
'clearInterval',
|
||||
'XMLHttpRequest',
|
||||
'Date'
|
||||
];
|
||||
|
||||
/**
|
||||
* Expose `Runner`.
|
||||
*/
|
||||
|
||||
module.exports = Runner;
|
||||
|
||||
/**
|
||||
* Initialize a `Runner` for the given `suite`.
|
||||
*
|
||||
* Events:
|
||||
*
|
||||
* - `start` execution started
|
||||
* - `end` execution complete
|
||||
* - `suite` (suite) test suite execution started
|
||||
* - `suite end` (suite) all tests (and sub-suites) have finished
|
||||
* - `test` (test) test execution started
|
||||
* - `test end` (test) test completed
|
||||
* - `hook` (hook) hook execution started
|
||||
* - `hook end` (hook) hook complete
|
||||
* - `pass` (test) test passed
|
||||
* - `fail` (test, err) test failed
|
||||
* - `pending` (test) test pending
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function Runner(suite) {
|
||||
var self = this;
|
||||
this._globals = [];
|
||||
this._abort = false;
|
||||
this.suite = suite;
|
||||
this.total = suite.total();
|
||||
this.failures = 0;
|
||||
this.on('test end', function(test){ self.checkGlobals(test); });
|
||||
this.on('hook end', function(hook){ self.checkGlobals(hook); });
|
||||
this.grep(/.*/);
|
||||
this.globals(this.globalProps().concat(extraGlobals()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrapper for setImmediate, process.nextTick, or browser polyfill.
|
||||
*
|
||||
* @param {Function} fn
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Runner.immediately = global.setImmediate || process.nextTick;
|
||||
|
||||
/**
|
||||
* Inherit from `EventEmitter.prototype`.
|
||||
*/
|
||||
|
||||
Runner.prototype.__proto__ = EventEmitter.prototype;
|
||||
|
||||
/**
|
||||
* Run tests with full titles matching `re`. Updates runner.total
|
||||
* with number of tests matched.
|
||||
*
|
||||
* @param {RegExp} re
|
||||
* @param {Boolean} invert
|
||||
* @return {Runner} for chaining
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Runner.prototype.grep = function(re, invert){
|
||||
debug('grep %s', re);
|
||||
this._grep = re;
|
||||
this._invert = invert;
|
||||
this.total = this.grepTotal(this.suite);
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the number of tests matching the grep search for the
|
||||
* given suite.
|
||||
*
|
||||
* @param {Suite} suite
|
||||
* @return {Number}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Runner.prototype.grepTotal = function(suite) {
|
||||
var self = this;
|
||||
var total = 0;
|
||||
|
||||
suite.eachTest(function(test){
|
||||
var match = self._grep.test(test.fullTitle());
|
||||
if (self._invert) match = !match;
|
||||
if (match) total++;
|
||||
});
|
||||
|
||||
return total;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return a list of global properties.
|
||||
*
|
||||
* @return {Array}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Runner.prototype.globalProps = function() {
|
||||
var props = utils.keys(global);
|
||||
|
||||
// non-enumerables
|
||||
for (var i = 0; i < globals.length; ++i) {
|
||||
if (~utils.indexOf(props, globals[i])) continue;
|
||||
props.push(globals[i]);
|
||||
}
|
||||
|
||||
return props;
|
||||
};
|
||||
|
||||
/**
|
||||
* Allow the given `arr` of globals.
|
||||
*
|
||||
* @param {Array} arr
|
||||
* @return {Runner} for chaining
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Runner.prototype.globals = function(arr){
|
||||
if (0 == arguments.length) return this._globals;
|
||||
debug('globals %j', arr);
|
||||
this._globals = this._globals.concat(arr);
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Check for global variable leaks.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Runner.prototype.checkGlobals = function(test){
|
||||
if (this.ignoreLeaks) return;
|
||||
var ok = this._globals;
|
||||
|
||||
var globals = this.globalProps();
|
||||
var isNode = process.kill;
|
||||
var leaks;
|
||||
|
||||
if (test) {
|
||||
ok = ok.concat(test._allowedGlobals || []);
|
||||
}
|
||||
|
||||
if(this.prevGlobalsLength == globals.length) return;
|
||||
this.prevGlobalsLength = globals.length;
|
||||
|
||||
leaks = filterLeaks(ok, globals);
|
||||
this._globals = this._globals.concat(leaks);
|
||||
|
||||
if (leaks.length > 1) {
|
||||
this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + ''));
|
||||
} else if (leaks.length) {
|
||||
this.fail(test, new Error('global leak detected: ' + leaks[0]));
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Fail the given `test`.
|
||||
*
|
||||
* @param {Test} test
|
||||
* @param {Error} err
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Runner.prototype.fail = function(test, err){
|
||||
++this.failures;
|
||||
test.state = 'failed';
|
||||
|
||||
if ('string' == typeof err) {
|
||||
err = new Error('the string "' + err + '" was thrown, throw an Error :)');
|
||||
}
|
||||
|
||||
this.emit('fail', test, err);
|
||||
};
|
||||
|
||||
/**
|
||||
* Fail the given `hook` with `err`.
|
||||
*
|
||||
* Hook failures work in the following pattern:
|
||||
* - If bail, then exit
|
||||
* - Failed `before` hook skips all tests in a suite and subsuites,
|
||||
* but jumps to corresponding `after` hook
|
||||
* - Failed `before each` hook skips remaining tests in a
|
||||
* suite and jumps to corresponding `after each` hook,
|
||||
* which is run only once
|
||||
* - Failed `after` hook does not alter
|
||||
* execution order
|
||||
* - Failed `after each` hook skips remaining tests in a
|
||||
* suite and subsuites, but executes other `after each`
|
||||
* hooks
|
||||
*
|
||||
* @param {Hook} hook
|
||||
* @param {Error} err
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Runner.prototype.failHook = function(hook, err){
|
||||
this.fail(hook, err);
|
||||
if (this.suite.bail()) {
|
||||
this.emit('end');
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Run hook `name` callbacks and then invoke `fn()`.
|
||||
*
|
||||
* @param {String} name
|
||||
* @param {Function} function
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Runner.prototype.hook = function(name, fn){
|
||||
var suite = this.suite
|
||||
, hooks = suite['_' + name]
|
||||
, self = this
|
||||
, timer;
|
||||
|
||||
function next(i) {
|
||||
var hook = hooks[i];
|
||||
if (!hook) return fn();
|
||||
if (self.failures && suite.bail()) return fn();
|
||||
self.currentRunnable = hook;
|
||||
|
||||
hook.ctx.currentTest = self.test;
|
||||
|
||||
self.emit('hook', hook);
|
||||
|
||||
hook.on('error', function(err){
|
||||
self.failHook(hook, err);
|
||||
});
|
||||
|
||||
hook.run(function(err){
|
||||
hook.removeAllListeners('error');
|
||||
var testError = hook.error();
|
||||
if (testError) self.fail(self.test, testError);
|
||||
if (err) {
|
||||
self.failHook(hook, err);
|
||||
|
||||
// stop executing hooks, notify callee of hook err
|
||||
return fn(err);
|
||||
}
|
||||
self.emit('hook end', hook);
|
||||
delete hook.ctx.currentTest;
|
||||
next(++i);
|
||||
});
|
||||
}
|
||||
|
||||
Runner.immediately(function(){
|
||||
next(0);
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Run hook `name` for the given array of `suites`
|
||||
* in order, and callback `fn(err, errSuite)`.
|
||||
*
|
||||
* @param {String} name
|
||||
* @param {Array} suites
|
||||
* @param {Function} fn
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Runner.prototype.hooks = function(name, suites, fn){
|
||||
var self = this
|
||||
, orig = this.suite;
|
||||
|
||||
function next(suite) {
|
||||
self.suite = suite;
|
||||
|
||||
if (!suite) {
|
||||
self.suite = orig;
|
||||
return fn();
|
||||
}
|
||||
|
||||
self.hook(name, function(err){
|
||||
if (err) {
|
||||
var errSuite = self.suite;
|
||||
self.suite = orig;
|
||||
return fn(err, errSuite);
|
||||
}
|
||||
|
||||
next(suites.pop());
|
||||
});
|
||||
}
|
||||
|
||||
next(suites.pop());
|
||||
};
|
||||
|
||||
/**
|
||||
* Run hooks from the top level down.
|
||||
*
|
||||
* @param {String} name
|
||||
* @param {Function} fn
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Runner.prototype.hookUp = function(name, fn){
|
||||
var suites = [this.suite].concat(this.parents()).reverse();
|
||||
this.hooks(name, suites, fn);
|
||||
};
|
||||
|
||||
/**
|
||||
* Run hooks from the bottom up.
|
||||
*
|
||||
* @param {String} name
|
||||
* @param {Function} fn
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Runner.prototype.hookDown = function(name, fn){
|
||||
var suites = [this.suite].concat(this.parents());
|
||||
this.hooks(name, suites, fn);
|
||||
};
|
||||
|
||||
/**
|
||||
* Return an array of parent Suites from
|
||||
* closest to furthest.
|
||||
*
|
||||
* @return {Array}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Runner.prototype.parents = function(){
|
||||
var suite = this.suite
|
||||
, suites = [];
|
||||
while (suite = suite.parent) suites.push(suite);
|
||||
return suites;
|
||||
};
|
||||
|
||||
/**
|
||||
* Run the current test and callback `fn(err)`.
|
||||
*
|
||||
* @param {Function} fn
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Runner.prototype.runTest = function(fn){
|
||||
var test = this.test
|
||||
, self = this;
|
||||
|
||||
if (this.asyncOnly) test.asyncOnly = true;
|
||||
|
||||
try {
|
||||
test.on('error', function(err){
|
||||
self.fail(test, err);
|
||||
});
|
||||
test.run(fn);
|
||||
} catch (err) {
|
||||
fn(err);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Run tests in the given `suite` and invoke
|
||||
* the callback `fn()` when complete.
|
||||
*
|
||||
* @param {Suite} suite
|
||||
* @param {Function} fn
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Runner.prototype.runTests = function(suite, fn){
|
||||
var self = this
|
||||
, tests = suite.tests.slice()
|
||||
, test;
|
||||
|
||||
|
||||
function hookErr(err, errSuite, after) {
|
||||
// before/after Each hook for errSuite failed:
|
||||
var orig = self.suite;
|
||||
|
||||
// for failed 'after each' hook start from errSuite parent,
|
||||
// otherwise start from errSuite itself
|
||||
self.suite = after ? errSuite.parent : errSuite;
|
||||
|
||||
if (self.suite) {
|
||||
// call hookUp afterEach
|
||||
self.hookUp('afterEach', function(err2, errSuite2) {
|
||||
self.suite = orig;
|
||||
// some hooks may fail even now
|
||||
if (err2) return hookErr(err2, errSuite2, true);
|
||||
// report error suite
|
||||
fn(errSuite);
|
||||
});
|
||||
} else {
|
||||
// there is no need calling other 'after each' hooks
|
||||
self.suite = orig;
|
||||
fn(errSuite);
|
||||
}
|
||||
}
|
||||
|
||||
function next(err, errSuite) {
|
||||
// if we bail after first err
|
||||
if (self.failures && suite._bail) return fn();
|
||||
|
||||
if (self._abort) return fn();
|
||||
|
||||
if (err) return hookErr(err, errSuite, true);
|
||||
|
||||
// next test
|
||||
test = tests.shift();
|
||||
|
||||
// all done
|
||||
if (!test) return fn();
|
||||
|
||||
// grep
|
||||
var match = self._grep.test(test.fullTitle());
|
||||
if (self._invert) match = !match;
|
||||
if (!match) return next();
|
||||
|
||||
// pending
|
||||
if (test.pending) {
|
||||
self.emit('pending', test);
|
||||
self.emit('test end', test);
|
||||
return next();
|
||||
}
|
||||
|
||||
// execute test and hook(s)
|
||||
self.emit('test', self.test = test);
|
||||
self.hookDown('beforeEach', function(err, errSuite){
|
||||
|
||||
if (err) return hookErr(err, errSuite, false);
|
||||
|
||||
self.currentRunnable = self.test;
|
||||
self.runTest(function(err){
|
||||
test = self.test;
|
||||
|
||||
if (err) {
|
||||
self.fail(test, err);
|
||||
self.emit('test end', test);
|
||||
return self.hookUp('afterEach', next);
|
||||
}
|
||||
|
||||
test.state = 'passed';
|
||||
self.emit('pass', test);
|
||||
self.emit('test end', test);
|
||||
self.hookUp('afterEach', next);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
this.next = next;
|
||||
next();
|
||||
};
|
||||
|
||||
/**
|
||||
* Run the given `suite` and invoke the
|
||||
* callback `fn()` when complete.
|
||||
*
|
||||
* @param {Suite} suite
|
||||
* @param {Function} fn
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Runner.prototype.runSuite = function(suite, fn){
|
||||
var total = this.grepTotal(suite)
|
||||
, self = this
|
||||
, i = 0;
|
||||
|
||||
debug('run suite %s', suite.fullTitle());
|
||||
|
||||
if (!total) return fn();
|
||||
|
||||
this.emit('suite', this.suite = suite);
|
||||
|
||||
function next(errSuite) {
|
||||
if (errSuite) {
|
||||
// current suite failed on a hook from errSuite
|
||||
if (errSuite == suite) {
|
||||
// if errSuite is current suite
|
||||
// continue to the next sibling suite
|
||||
return done();
|
||||
} else {
|
||||
// errSuite is among the parents of current suite
|
||||
// stop execution of errSuite and all sub-suites
|
||||
return done(errSuite);
|
||||
}
|
||||
}
|
||||
|
||||
if (self._abort) return done();
|
||||
|
||||
var curr = suite.suites[i++];
|
||||
if (!curr) return done();
|
||||
self.runSuite(curr, next);
|
||||
}
|
||||
|
||||
function done(errSuite) {
|
||||
self.suite = suite;
|
||||
self.hook('afterAll', function(){
|
||||
self.emit('suite end', suite);
|
||||
fn(errSuite);
|
||||
});
|
||||
}
|
||||
|
||||
this.hook('beforeAll', function(err){
|
||||
if (err) return done();
|
||||
self.runTests(suite, next);
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Handle uncaught exceptions.
|
||||
*
|
||||
* @param {Error} err
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Runner.prototype.uncaught = function(err){
|
||||
debug('uncaught exception %s', err.message);
|
||||
var runnable = this.currentRunnable;
|
||||
if (!runnable || 'failed' == runnable.state) return;
|
||||
runnable.clearTimeout();
|
||||
err.uncaught = true;
|
||||
this.fail(runnable, err);
|
||||
|
||||
// recover from test
|
||||
if ('test' == runnable.type) {
|
||||
this.emit('test end', runnable);
|
||||
this.hookUp('afterEach', this.next);
|
||||
return;
|
||||
}
|
||||
|
||||
// bail on hooks
|
||||
this.emit('end');
|
||||
};
|
||||
|
||||
/**
|
||||
* Run the root suite and invoke `fn(failures)`
|
||||
* on completion.
|
||||
*
|
||||
* @param {Function} fn
|
||||
* @return {Runner} for chaining
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Runner.prototype.run = function(fn){
|
||||
var self = this
|
||||
, fn = fn || function(){};
|
||||
|
||||
function uncaught(err){
|
||||
self.uncaught(err);
|
||||
}
|
||||
|
||||
debug('start');
|
||||
|
||||
// callback
|
||||
this.on('end', function(){
|
||||
debug('end');
|
||||
process.removeListener('uncaughtException', uncaught);
|
||||
fn(self.failures);
|
||||
});
|
||||
|
||||
// run suites
|
||||
this.emit('start');
|
||||
this.runSuite(this.suite, function(){
|
||||
debug('finished running');
|
||||
self.emit('end');
|
||||
});
|
||||
|
||||
// uncaught exception
|
||||
process.on('uncaughtException', uncaught);
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Cleanly abort execution
|
||||
*
|
||||
* @return {Runner} for chaining
|
||||
* @api public
|
||||
*/
|
||||
Runner.prototype.abort = function(){
|
||||
debug('aborting');
|
||||
this._abort = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter leaks with the given globals flagged as `ok`.
|
||||
*
|
||||
* @param {Array} ok
|
||||
* @param {Array} globals
|
||||
* @return {Array}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function filterLeaks(ok, globals) {
|
||||
return filter(globals, function(key){
|
||||
// Firefox and Chrome exposes iframes as index inside the window object
|
||||
if (/^d+/.test(key)) return false;
|
||||
|
||||
// in firefox
|
||||
// if runner runs in an iframe, this iframe's window.getInterface method not init at first
|
||||
// it is assigned in some seconds
|
||||
if (global.navigator && /^getInterface/.test(key)) return false;
|
||||
|
||||
// an iframe could be approached by window[iframeIndex]
|
||||
// in ie6,7,8 and opera, iframeIndex is enumerable, this could cause leak
|
||||
if (global.navigator && /^\d+/.test(key)) return false;
|
||||
|
||||
// Opera and IE expose global variables for HTML element IDs (issue #243)
|
||||
if (/^mocha-/.test(key)) return false;
|
||||
|
||||
var matched = filter(ok, function(ok){
|
||||
if (~ok.indexOf('*')) return 0 == key.indexOf(ok.split('*')[0]);
|
||||
return key == ok;
|
||||
});
|
||||
return matched.length == 0 && (!global.navigator || 'onerror' !== key);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Array of globals dependent on the environment.
|
||||
*
|
||||
* @return {Array}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function extraGlobals() {
|
||||
if (typeof(process) === 'object' &&
|
||||
typeof(process.version) === 'string') {
|
||||
|
||||
var nodeVersion = process.version.split('.').reduce(function(a, v) {
|
||||
return a << 8 | v;
|
||||
});
|
||||
|
||||
// 'errno' was renamed to process._errno in v0.9.11.
|
||||
|
||||
if (nodeVersion < 0x00090B) {
|
||||
return ['errno'];
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
+296
@@ -0,0 +1,296 @@
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var EventEmitter = require('events').EventEmitter
|
||||
, debug = require('debug')('mocha:suite')
|
||||
, milliseconds = require('./ms')
|
||||
, utils = require('./utils')
|
||||
, Hook = require('./hook');
|
||||
|
||||
/**
|
||||
* Expose `Suite`.
|
||||
*/
|
||||
|
||||
exports = module.exports = Suite;
|
||||
|
||||
/**
|
||||
* Create a new `Suite` with the given `title`
|
||||
* and parent `Suite`. When a suite with the
|
||||
* same title is already present, that suite
|
||||
* is returned to provide nicer reporter
|
||||
* and more flexible meta-testing.
|
||||
*
|
||||
* @param {Suite} parent
|
||||
* @param {String} title
|
||||
* @return {Suite}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
exports.create = function(parent, title){
|
||||
var suite = new Suite(title, parent.ctx);
|
||||
suite.parent = parent;
|
||||
if (parent.pending) suite.pending = true;
|
||||
title = suite.fullTitle();
|
||||
parent.addSuite(suite);
|
||||
return suite;
|
||||
};
|
||||
|
||||
/**
|
||||
* Initialize a new `Suite` with the given
|
||||
* `title` and `ctx`.
|
||||
*
|
||||
* @param {String} title
|
||||
* @param {Context} ctx
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function Suite(title, ctx) {
|
||||
this.title = title;
|
||||
this.ctx = ctx;
|
||||
this.suites = [];
|
||||
this.tests = [];
|
||||
this.pending = false;
|
||||
this._beforeEach = [];
|
||||
this._beforeAll = [];
|
||||
this._afterEach = [];
|
||||
this._afterAll = [];
|
||||
this.root = !title;
|
||||
this._timeout = 2000;
|
||||
this._slow = 75;
|
||||
this._bail = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inherit from `EventEmitter.prototype`.
|
||||
*/
|
||||
|
||||
Suite.prototype.__proto__ = EventEmitter.prototype;
|
||||
|
||||
/**
|
||||
* Return a clone of this `Suite`.
|
||||
*
|
||||
* @return {Suite}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Suite.prototype.clone = function(){
|
||||
var suite = new Suite(this.title);
|
||||
debug('clone');
|
||||
suite.ctx = this.ctx;
|
||||
suite.timeout(this.timeout());
|
||||
suite.slow(this.slow());
|
||||
suite.bail(this.bail());
|
||||
return suite;
|
||||
};
|
||||
|
||||
/**
|
||||
* Set timeout `ms` or short-hand such as "2s".
|
||||
*
|
||||
* @param {Number|String} ms
|
||||
* @return {Suite|Number} for chaining
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Suite.prototype.timeout = function(ms){
|
||||
if (0 == arguments.length) return this._timeout;
|
||||
if ('string' == typeof ms) ms = milliseconds(ms);
|
||||
debug('timeout %d', ms);
|
||||
this._timeout = parseInt(ms, 10);
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Set slow `ms` or short-hand such as "2s".
|
||||
*
|
||||
* @param {Number|String} ms
|
||||
* @return {Suite|Number} for chaining
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Suite.prototype.slow = function(ms){
|
||||
if (0 === arguments.length) return this._slow;
|
||||
if ('string' == typeof ms) ms = milliseconds(ms);
|
||||
debug('slow %d', ms);
|
||||
this._slow = ms;
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets whether to bail after first error.
|
||||
*
|
||||
* @parma {Boolean} bail
|
||||
* @return {Suite|Number} for chaining
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Suite.prototype.bail = function(bail){
|
||||
if (0 == arguments.length) return this._bail;
|
||||
debug('bail %s', bail);
|
||||
this._bail = bail;
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Run `fn(test[, done])` before running tests.
|
||||
*
|
||||
* @param {Function} fn
|
||||
* @return {Suite} for chaining
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Suite.prototype.beforeAll = function(fn){
|
||||
if (this.pending) return this;
|
||||
var hook = new Hook('"before all" hook', fn);
|
||||
hook.parent = this;
|
||||
hook.timeout(this.timeout());
|
||||
hook.slow(this.slow());
|
||||
hook.ctx = this.ctx;
|
||||
this._beforeAll.push(hook);
|
||||
this.emit('beforeAll', hook);
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Run `fn(test[, done])` after running tests.
|
||||
*
|
||||
* @param {Function} fn
|
||||
* @return {Suite} for chaining
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Suite.prototype.afterAll = function(fn){
|
||||
if (this.pending) return this;
|
||||
var hook = new Hook('"after all" hook', fn);
|
||||
hook.parent = this;
|
||||
hook.timeout(this.timeout());
|
||||
hook.slow(this.slow());
|
||||
hook.ctx = this.ctx;
|
||||
this._afterAll.push(hook);
|
||||
this.emit('afterAll', hook);
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Run `fn(test[, done])` before each test case.
|
||||
*
|
||||
* @param {Function} fn
|
||||
* @return {Suite} for chaining
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Suite.prototype.beforeEach = function(fn){
|
||||
if (this.pending) return this;
|
||||
var hook = new Hook('"before each" hook', fn);
|
||||
hook.parent = this;
|
||||
hook.timeout(this.timeout());
|
||||
hook.slow(this.slow());
|
||||
hook.ctx = this.ctx;
|
||||
this._beforeEach.push(hook);
|
||||
this.emit('beforeEach', hook);
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Run `fn(test[, done])` after each test case.
|
||||
*
|
||||
* @param {Function} fn
|
||||
* @return {Suite} for chaining
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Suite.prototype.afterEach = function(fn){
|
||||
if (this.pending) return this;
|
||||
var hook = new Hook('"after each" hook', fn);
|
||||
hook.parent = this;
|
||||
hook.timeout(this.timeout());
|
||||
hook.slow(this.slow());
|
||||
hook.ctx = this.ctx;
|
||||
this._afterEach.push(hook);
|
||||
this.emit('afterEach', hook);
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a test `suite`.
|
||||
*
|
||||
* @param {Suite} suite
|
||||
* @return {Suite} for chaining
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Suite.prototype.addSuite = function(suite){
|
||||
suite.parent = this;
|
||||
suite.timeout(this.timeout());
|
||||
suite.slow(this.slow());
|
||||
suite.bail(this.bail());
|
||||
this.suites.push(suite);
|
||||
this.emit('suite', suite);
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a `test` to this suite.
|
||||
*
|
||||
* @param {Test} test
|
||||
* @return {Suite} for chaining
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Suite.prototype.addTest = function(test){
|
||||
test.parent = this;
|
||||
test.timeout(this.timeout());
|
||||
test.slow(this.slow());
|
||||
test.ctx = this.ctx;
|
||||
this.tests.push(test);
|
||||
this.emit('test', test);
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the full title generated by recursively
|
||||
* concatenating the parent's full title.
|
||||
*
|
||||
* @return {String}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Suite.prototype.fullTitle = function(){
|
||||
if (this.parent) {
|
||||
var full = this.parent.fullTitle();
|
||||
if (full) return full + ' ' + this.title;
|
||||
}
|
||||
return this.title;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the total number of tests.
|
||||
*
|
||||
* @return {Number}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Suite.prototype.total = function(){
|
||||
return utils.reduce(this.suites, function(sum, suite){
|
||||
return sum + suite.total();
|
||||
}, 0) + this.tests.length;
|
||||
};
|
||||
|
||||
/**
|
||||
* Iterates through each suite recursively to find
|
||||
* all tests. Applies a function in the format
|
||||
* `fn(test)`.
|
||||
*
|
||||
* @param {Function} fn
|
||||
* @return {Suite}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Suite.prototype.eachTest = function(fn){
|
||||
utils.forEach(this.tests, fn);
|
||||
utils.forEach(this.suites, function(suite){
|
||||
suite.eachTest(fn);
|
||||
});
|
||||
return this;
|
||||
};
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Mocha</title>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<link rel="stylesheet" href="mocha.css" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="mocha"></div>
|
||||
<script src="mocha.js"></script>
|
||||
<script>mocha.setup('bdd')</script>
|
||||
<script src="tests.js"></script>
|
||||
<script>
|
||||
mocha.run();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var Runnable = require('./runnable');
|
||||
|
||||
/**
|
||||
* Expose `Test`.
|
||||
*/
|
||||
|
||||
module.exports = Test;
|
||||
|
||||
/**
|
||||
* Initialize a new `Test` with the given `title` and callback `fn`.
|
||||
*
|
||||
* @param {String} title
|
||||
* @param {Function} fn
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function Test(title, fn) {
|
||||
Runnable.call(this, title, fn);
|
||||
this.pending = !fn;
|
||||
this.type = 'test';
|
||||
}
|
||||
|
||||
/**
|
||||
* Inherit from `Runnable.prototype`.
|
||||
*/
|
||||
|
||||
Test.prototype.__proto__ = Runnable.prototype;
|
||||
+299
@@ -0,0 +1,299 @@
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var fs = require('fs')
|
||||
, path = require('path')
|
||||
, join = path.join
|
||||
, debug = require('debug')('mocha:watch');
|
||||
|
||||
/**
|
||||
* Ignored directories.
|
||||
*/
|
||||
|
||||
var ignore = ['node_modules', '.git'];
|
||||
|
||||
/**
|
||||
* Escape special characters in the given string of html.
|
||||
*
|
||||
* @param {String} html
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
exports.escape = function(html){
|
||||
return String(html)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>');
|
||||
};
|
||||
|
||||
/**
|
||||
* Array#forEach (<=IE8)
|
||||
*
|
||||
* @param {Array} array
|
||||
* @param {Function} fn
|
||||
* @param {Object} scope
|
||||
* @api private
|
||||
*/
|
||||
|
||||
exports.forEach = function(arr, fn, scope){
|
||||
for (var i = 0, l = arr.length; i < l; i++)
|
||||
fn.call(scope, arr[i], i);
|
||||
};
|
||||
|
||||
/**
|
||||
* Array#map (<=IE8)
|
||||
*
|
||||
* @param {Array} array
|
||||
* @param {Function} fn
|
||||
* @param {Object} scope
|
||||
* @api private
|
||||
*/
|
||||
|
||||
exports.map = function(arr, fn, scope){
|
||||
var result = [];
|
||||
for (var i = 0, l = arr.length; i < l; i++)
|
||||
result.push(fn.call(scope, arr[i], i));
|
||||
return result;
|
||||
};
|
||||
|
||||
/**
|
||||
* Array#indexOf (<=IE8)
|
||||
*
|
||||
* @parma {Array} arr
|
||||
* @param {Object} obj to find index of
|
||||
* @param {Number} start
|
||||
* @api private
|
||||
*/
|
||||
|
||||
exports.indexOf = function(arr, obj, start){
|
||||
for (var i = start || 0, l = arr.length; i < l; i++) {
|
||||
if (arr[i] === obj)
|
||||
return i;
|
||||
}
|
||||
return -1;
|
||||
};
|
||||
|
||||
/**
|
||||
* Array#reduce (<=IE8)
|
||||
*
|
||||
* @param {Array} array
|
||||
* @param {Function} fn
|
||||
* @param {Object} initial value
|
||||
* @api private
|
||||
*/
|
||||
|
||||
exports.reduce = function(arr, fn, val){
|
||||
var rval = val;
|
||||
|
||||
for (var i = 0, l = arr.length; i < l; i++) {
|
||||
rval = fn(rval, arr[i], i, arr);
|
||||
}
|
||||
|
||||
return rval;
|
||||
};
|
||||
|
||||
/**
|
||||
* Array#filter (<=IE8)
|
||||
*
|
||||
* @param {Array} array
|
||||
* @param {Function} fn
|
||||
* @api private
|
||||
*/
|
||||
|
||||
exports.filter = function(arr, fn){
|
||||
var ret = [];
|
||||
|
||||
for (var i = 0, l = arr.length; i < l; i++) {
|
||||
var val = arr[i];
|
||||
if (fn(val, i, arr)) ret.push(val);
|
||||
}
|
||||
|
||||
return ret;
|
||||
};
|
||||
|
||||
/**
|
||||
* Object.keys (<=IE8)
|
||||
*
|
||||
* @param {Object} obj
|
||||
* @return {Array} keys
|
||||
* @api private
|
||||
*/
|
||||
|
||||
exports.keys = Object.keys || function(obj) {
|
||||
var keys = []
|
||||
, has = Object.prototype.hasOwnProperty // for `window` on <=IE8
|
||||
|
||||
for (var key in obj) {
|
||||
if (has.call(obj, key)) {
|
||||
keys.push(key);
|
||||
}
|
||||
}
|
||||
|
||||
return keys;
|
||||
};
|
||||
|
||||
/**
|
||||
* Watch the given `files` for changes
|
||||
* and invoke `fn(file)` on modification.
|
||||
*
|
||||
* @param {Array} files
|
||||
* @param {Function} fn
|
||||
* @api private
|
||||
*/
|
||||
|
||||
exports.watch = function(files, fn){
|
||||
var options = { interval: 100 };
|
||||
files.forEach(function(file){
|
||||
debug('file %s', file);
|
||||
fs.watchFile(file, options, function(curr, prev){
|
||||
if (prev.mtime < curr.mtime) fn(file);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Ignored files.
|
||||
*/
|
||||
|
||||
function ignored(path){
|
||||
return !~ignore.indexOf(path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lookup files in the given `dir`.
|
||||
*
|
||||
* @return {Array}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
exports.files = function(dir, ret){
|
||||
ret = ret || [];
|
||||
|
||||
fs.readdirSync(dir)
|
||||
.filter(ignored)
|
||||
.forEach(function(path){
|
||||
path = join(dir, path);
|
||||
if (fs.statSync(path).isDirectory()) {
|
||||
exports.files(path, ret);
|
||||
} else if (path.match(/\.(js|coffee|litcoffee|coffee.md)$/)) {
|
||||
ret.push(path);
|
||||
}
|
||||
});
|
||||
|
||||
return ret;
|
||||
};
|
||||
|
||||
/**
|
||||
* Compute a slug from the given `str`.
|
||||
*
|
||||
* @param {String} str
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
exports.slug = function(str){
|
||||
return str
|
||||
.toLowerCase()
|
||||
.replace(/ +/g, '-')
|
||||
.replace(/[^-\w]/g, '');
|
||||
};
|
||||
|
||||
/**
|
||||
* Strip the function definition from `str`,
|
||||
* and re-indent for pre whitespace.
|
||||
*/
|
||||
|
||||
exports.clean = function(str) {
|
||||
str = str
|
||||
.replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, '')
|
||||
.replace(/^function *\(.*\) *{/, '')
|
||||
.replace(/\s+\}$/, '');
|
||||
|
||||
var spaces = str.match(/^\n?( *)/)[1].length
|
||||
, tabs = str.match(/^\n?(\t*)/)[1].length
|
||||
, re = new RegExp('^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs ? tabs : spaces) + '}', 'gm');
|
||||
|
||||
str = str.replace(re, '');
|
||||
|
||||
return exports.trim(str);
|
||||
};
|
||||
|
||||
/**
|
||||
* Escape regular expression characters in `str`.
|
||||
*
|
||||
* @param {String} str
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
exports.escapeRegexp = function(str){
|
||||
return str.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&");
|
||||
};
|
||||
|
||||
/**
|
||||
* Trim the given `str`.
|
||||
*
|
||||
* @param {String} str
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
exports.trim = function(str){
|
||||
return str.replace(/^\s+|\s+$/g, '');
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse the given `qs`.
|
||||
*
|
||||
* @param {String} qs
|
||||
* @return {Object}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
exports.parseQuery = function(qs){
|
||||
return exports.reduce(qs.replace('?', '').split('&'), function(obj, pair){
|
||||
var i = pair.indexOf('=')
|
||||
, key = pair.slice(0, i)
|
||||
, val = pair.slice(++i);
|
||||
|
||||
obj[key] = decodeURIComponent(val);
|
||||
return obj;
|
||||
}, {});
|
||||
};
|
||||
|
||||
/**
|
||||
* Highlight the given string of `js`.
|
||||
*
|
||||
* @param {String} js
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function highlight(js) {
|
||||
return js
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/\/\/(.*)/gm, '<span class="comment">//$1</span>')
|
||||
.replace(/('.*?')/gm, '<span class="string">$1</span>')
|
||||
.replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>')
|
||||
.replace(/(\d+)/gm, '<span class="number">$1</span>')
|
||||
.replace(/\bnew *(\w+)/gm, '<span class="keyword">new</span> <span class="init">$1</span>')
|
||||
.replace(/\b(function|new|throw|return|var|if|else)\b/gm, '<span class="keyword">$1</span>')
|
||||
}
|
||||
|
||||
/**
|
||||
* Highlight the contents of tag `name`.
|
||||
*
|
||||
* @param {String} name
|
||||
* @api private
|
||||
*/
|
||||
|
||||
exports.highlightTags = function(name) {
|
||||
var code = document.getElementsByTagName(name);
|
||||
for (var i = 0, len = code.length; i < len; ++i) {
|
||||
code[i].innerHTML = highlight(code[i].innerHTML);
|
||||
}
|
||||
};
|
||||
+270
@@ -0,0 +1,270 @@
|
||||
@charset "utf-8";
|
||||
|
||||
body {
|
||||
margin:0;
|
||||
}
|
||||
|
||||
#mocha {
|
||||
font: 20px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif;
|
||||
margin: 60px 50px;
|
||||
}
|
||||
|
||||
#mocha ul,
|
||||
#mocha li {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
#mocha ul {
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
#mocha h1,
|
||||
#mocha h2 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
#mocha h1 {
|
||||
margin-top: 15px;
|
||||
font-size: 1em;
|
||||
font-weight: 200;
|
||||
}
|
||||
|
||||
#mocha h1 a {
|
||||
text-decoration: none;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
#mocha h1 a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
#mocha .suite .suite h1 {
|
||||
margin-top: 0;
|
||||
font-size: .8em;
|
||||
}
|
||||
|
||||
#mocha .hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#mocha h2 {
|
||||
font-size: 12px;
|
||||
font-weight: normal;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
#mocha .suite {
|
||||
margin-left: 15px;
|
||||
}
|
||||
|
||||
#mocha .test {
|
||||
margin-left: 15px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
#mocha .test.pending:hover h2::after {
|
||||
content: '(pending)';
|
||||
font-family: arial, sans-serif;
|
||||
}
|
||||
|
||||
#mocha .test.pass.medium .duration {
|
||||
background: #c09853;
|
||||
}
|
||||
|
||||
#mocha .test.pass.slow .duration {
|
||||
background: #b94a48;
|
||||
}
|
||||
|
||||
#mocha .test.pass::before {
|
||||
content: '✓';
|
||||
font-size: 12px;
|
||||
display: block;
|
||||
float: left;
|
||||
margin-right: 5px;
|
||||
color: #00d6b2;
|
||||
}
|
||||
|
||||
#mocha .test.pass .duration {
|
||||
font-size: 9px;
|
||||
margin-left: 5px;
|
||||
padding: 2px 5px;
|
||||
color: #fff;
|
||||
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
|
||||
-moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
|
||||
box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
|
||||
-webkit-border-radius: 5px;
|
||||
-moz-border-radius: 5px;
|
||||
-ms-border-radius: 5px;
|
||||
-o-border-radius: 5px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
#mocha .test.pass.fast .duration {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#mocha .test.pending {
|
||||
color: #0b97c4;
|
||||
}
|
||||
|
||||
#mocha .test.pending::before {
|
||||
content: '◦';
|
||||
color: #0b97c4;
|
||||
}
|
||||
|
||||
#mocha .test.fail {
|
||||
color: #c00;
|
||||
}
|
||||
|
||||
#mocha .test.fail pre {
|
||||
color: black;
|
||||
}
|
||||
|
||||
#mocha .test.fail::before {
|
||||
content: '✖';
|
||||
font-size: 12px;
|
||||
display: block;
|
||||
float: left;
|
||||
margin-right: 5px;
|
||||
color: #c00;
|
||||
}
|
||||
|
||||
#mocha .test pre.error {
|
||||
color: #c00;
|
||||
max-height: 300px;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
/**
|
||||
* (1): approximate for browsers not supporting calc
|
||||
* (2): 42 = 2*15 + 2*10 + 2*1 (padding + margin + border)
|
||||
* ^^ seriously
|
||||
*/
|
||||
#mocha .test pre {
|
||||
display: block;
|
||||
float: left;
|
||||
clear: left;
|
||||
font: 12px/1.5 monaco, monospace;
|
||||
margin: 5px;
|
||||
padding: 15px;
|
||||
border: 1px solid #eee;
|
||||
max-width: 85%; /*(1)*/
|
||||
max-width: calc(100% - 42px); /*(2)*/
|
||||
word-wrap: break-word;
|
||||
border-bottom-color: #ddd;
|
||||
-webkit-border-radius: 3px;
|
||||
-webkit-box-shadow: 0 1px 3px #eee;
|
||||
-moz-border-radius: 3px;
|
||||
-moz-box-shadow: 0 1px 3px #eee;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
#mocha .test h2 {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
#mocha .test a.replay {
|
||||
position: absolute;
|
||||
top: 3px;
|
||||
right: 0;
|
||||
text-decoration: none;
|
||||
vertical-align: middle;
|
||||
display: block;
|
||||
width: 15px;
|
||||
height: 15px;
|
||||
line-height: 15px;
|
||||
text-align: center;
|
||||
background: #eee;
|
||||
font-size: 15px;
|
||||
-moz-border-radius: 15px;
|
||||
border-radius: 15px;
|
||||
-webkit-transition: opacity 200ms;
|
||||
-moz-transition: opacity 200ms;
|
||||
transition: opacity 200ms;
|
||||
opacity: 0.3;
|
||||
color: #888;
|
||||
}
|
||||
|
||||
#mocha .test:hover a.replay {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
#mocha-report.pass .test.fail {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#mocha-report.fail .test.pass {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#mocha-report.pending .test.pass,
|
||||
#mocha-report.pending .test.fail {
|
||||
display: none;
|
||||
}
|
||||
#mocha-report.pending .test.pass.pending {
|
||||
display: block;
|
||||
}
|
||||
|
||||
#mocha-error {
|
||||
color: #c00;
|
||||
font-size: 1.5em;
|
||||
font-weight: 100;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
#mocha-stats {
|
||||
position: fixed;
|
||||
top: 15px;
|
||||
right: 10px;
|
||||
font-size: 12px;
|
||||
margin: 0;
|
||||
color: #888;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
#mocha-stats .progress {
|
||||
float: right;
|
||||
padding-top: 0;
|
||||
}
|
||||
|
||||
#mocha-stats em {
|
||||
color: black;
|
||||
}
|
||||
|
||||
#mocha-stats a {
|
||||
text-decoration: none;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
#mocha-stats a:hover {
|
||||
border-bottom: 1px solid #eee;
|
||||
}
|
||||
|
||||
#mocha-stats li {
|
||||
display: inline-block;
|
||||
margin: 0 5px;
|
||||
list-style: none;
|
||||
padding-top: 11px;
|
||||
}
|
||||
|
||||
#mocha-stats canvas {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
}
|
||||
|
||||
#mocha code .comment { color: #ddd; }
|
||||
#mocha code .init { color: #2f6fad; }
|
||||
#mocha code .string { color: #5890ad; }
|
||||
#mocha code .keyword { color: #8a6343; }
|
||||
#mocha code .number { color: #2f6fad; }
|
||||
|
||||
@media screen and (max-device-width: 480px) {
|
||||
#mocha {
|
||||
margin: 60px 0px;
|
||||
}
|
||||
|
||||
#mocha #stats {
|
||||
position: absolute;
|
||||
}
|
||||
}
|
||||
+5812
File diff suppressed because it is too large.
Load diff
+1
@@ -0,0 +1 @@
|
||||
../jade/bin/jade
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
|
||||
2.0.0 / 2013-07-18
|
||||
==================
|
||||
|
||||
* remove input methods (.prompt, .confirm, etc)
|
||||
|
||||
1.3.2 / 2013-07-18
|
||||
==================
|
||||
|
||||
* add support for sub-commands to co-exist with the original command
|
||||
|
||||
1.3.1 / 2013-07-18
|
||||
==================
|
||||
|
||||
* add quick .runningCommand hack so you can opt-out of other logic when running a sub command
|
||||
|
||||
1.3.0 / 2013-07-09
|
||||
==================
|
||||
|
||||
* add EACCES error handling
|
||||
* fix sub-command --help
|
||||
|
||||
1.2.0 / 2013-06-13
|
||||
==================
|
||||
|
||||
* allow "-" hyphen as an option argument
|
||||
* support for RegExp coercion
|
||||
|
||||
1.1.1 / 2012-11-20
|
||||
==================
|
||||
|
||||
* add more sub-command padding
|
||||
* fix .usage() when args are present. Closes #106
|
||||
|
||||
1.1.0 / 2012-11-16
|
||||
==================
|
||||
|
||||
* add git-style executable subcommand support. Closes #94
|
||||
|
||||
1.0.5 / 2012-10-09
|
||||
==================
|
||||
|
||||
* fix `--name` clobbering. Closes #92
|
||||
* fix examples/help. Closes #89
|
||||
|
||||
1.0.4 / 2012-09-03
|
||||
==================
|
||||
|
||||
* add `outputHelp()` method.
|
||||
|
||||
1.0.3 / 2012-08-30
|
||||
==================
|
||||
|
||||
* remove invalid .version() defaulting
|
||||
|
||||
1.0.2 / 2012-08-24
|
||||
==================
|
||||
|
||||
* add `--foo=bar` support [arv]
|
||||
* fix password on node 0.8.8. Make backward compatible with 0.6 [focusaurus]
|
||||
|
||||
1.0.1 / 2012-08-03
|
||||
==================
|
||||
|
||||
* fix issue #56
|
||||
* fix tty.setRawMode(mode) was moved to tty.ReadStream#setRawMode() (i.e. process.stdin.setRawMode())
|
||||
|
||||
1.0.0 / 2012-07-05
|
||||
==================
|
||||
|
||||
* add support for optional option descriptions
|
||||
* add defaulting of `.version()` to package.json's version
|
||||
|
||||
0.6.1 / 2012-06-01
|
||||
==================
|
||||
|
||||
* Added: append (yes or no) on confirmation
|
||||
* Added: allow node.js v0.7.x
|
||||
|
||||
0.6.0 / 2012-04-10
|
||||
==================
|
||||
|
||||
* Added `.prompt(obj, callback)` support. Closes #49
|
||||
* Added default support to .choose(). Closes #41
|
||||
* Fixed the choice example
|
||||
|
||||
0.5.1 / 2011-12-20
|
||||
==================
|
||||
|
||||
* Fixed `password()` for recent nodes. Closes #36
|
||||
|
||||
0.5.0 / 2011-12-04
|
||||
==================
|
||||
|
||||
* Added sub-command option support [itay]
|
||||
|
||||
0.4.3 / 2011-12-04
|
||||
==================
|
||||
|
||||
* Fixed custom help ordering. Closes #32
|
||||
|
||||
0.4.2 / 2011-11-24
|
||||
==================
|
||||
|
||||
* Added travis support
|
||||
* Fixed: line-buffered input automatically trimmed. Closes #31
|
||||
|
||||
0.4.1 / 2011-11-18
|
||||
==================
|
||||
|
||||
* Removed listening for "close" on --help
|
||||
|
||||
0.4.0 / 2011-11-15
|
||||
==================
|
||||
|
||||
* Added support for `--`. Closes #24
|
||||
|
||||
0.3.3 / 2011-11-14
|
||||
==================
|
||||
|
||||
* Fixed: wait for close event when writing help info [Jerry Hamlet]
|
||||
|
||||
0.3.2 / 2011-11-01
|
||||
==================
|
||||
|
||||
* Fixed long flag definitions with values [felixge]
|
||||
|
||||
0.3.1 / 2011-10-31
|
||||
==================
|
||||
|
||||
* Changed `--version` short flag to `-V` from `-v`
|
||||
* Changed `.version()` so it's configurable [felixge]
|
||||
|
||||
0.3.0 / 2011-10-31
|
||||
==================
|
||||
|
||||
* Added support for long flags only. Closes #18
|
||||
|
||||
0.2.1 / 2011-10-24
|
||||
==================
|
||||
|
||||
* "node": ">= 0.4.x < 0.7.0". Closes #20
|
||||
|
||||
0.2.0 / 2011-09-26
|
||||
==================
|
||||
|
||||
* Allow for defaults that are not just boolean. Default peassignment only occurs for --no-*, optional, and required arguments. [Jim Isaacs]
|
||||
|
||||
0.1.0 / 2011-08-24
|
||||
==================
|
||||
|
||||
* Added support for custom `--help` output
|
||||
|
||||
0.0.5 / 2011-08-18
|
||||
==================
|
||||
|
||||
* Changed: when the user enters nothing prompt for password again
|
||||
* Fixed issue with passwords beginning with numbers [NuckChorris]
|
||||
|
||||
0.0.4 / 2011-08-15
|
||||
==================
|
||||
|
||||
* Fixed `Commander#args`
|
||||
|
||||
0.0.3 / 2011-08-15
|
||||
==================
|
||||
|
||||
* Added default option value support
|
||||
|
||||
0.0.2 / 2011-08-15
|
||||
==================
|
||||
|
||||
* Added mask support to `Command#password(str[, mask], fn)`
|
||||
* Added `Command#password(str, fn)`
|
||||
|
||||
0.0.1 / 2010-01-03
|
||||
==================
|
||||
|
||||
* Initial release
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
# Commander.js
|
||||
|
||||
The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/visionmedia/commander).
|
||||
|
||||
[](http://travis-ci.org/visionmedia/commander.js)
|
||||
|
||||
## Installation
|
||||
|
||||
$ npm install commander
|
||||
|
||||
## Option parsing
|
||||
|
||||
Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options.
|
||||
|
||||
```js
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var program = require('commander');
|
||||
|
||||
program
|
||||
.version('0.0.1')
|
||||
.option('-p, --peppers', 'Add peppers')
|
||||
.option('-P, --pineapple', 'Add pineapple')
|
||||
.option('-b, --bbq', 'Add bbq sauce')
|
||||
.option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')
|
||||
.parse(process.argv);
|
||||
|
||||
console.log('you ordered a pizza with:');
|
||||
if (program.peppers) console.log(' - peppers');
|
||||
if (program.pineapple) console.log(' - pineapple');
|
||||
if (program.bbq) console.log(' - bbq');
|
||||
console.log(' - %s cheese', program.cheese);
|
||||
```
|
||||
|
||||
Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc.
|
||||
|
||||
## Automated --help
|
||||
|
||||
The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free:
|
||||
|
||||
```
|
||||
$ ./examples/pizza --help
|
||||
|
||||
Usage: pizza [options]
|
||||
|
||||
Options:
|
||||
|
||||
-V, --version output the version number
|
||||
-p, --peppers Add peppers
|
||||
-P, --pineapple Add pineapple
|
||||
-b, --bbq Add bbq sauce
|
||||
-c, --cheese <type> Add the specified type of cheese [marble]
|
||||
-h, --help output usage information
|
||||
|
||||
```
|
||||
|
||||
## Coercion
|
||||
|
||||
```js
|
||||
function range(val) {
|
||||
return val.split('..').map(Number);
|
||||
}
|
||||
|
||||
function list(val) {
|
||||
return val.split(',');
|
||||
}
|
||||
|
||||
program
|
||||
.version('0.0.1')
|
||||
.usage('[options] <file ...>')
|
||||
.option('-i, --integer <n>', 'An integer argument', parseInt)
|
||||
.option('-f, --float <n>', 'A float argument', parseFloat)
|
||||
.option('-r, --range <a>..<b>', 'A range', range)
|
||||
.option('-l, --list <items>', 'A list', list)
|
||||
.option('-o, --optional [value]', 'An optional value')
|
||||
.parse(process.argv);
|
||||
|
||||
console.log(' int: %j', program.integer);
|
||||
console.log(' float: %j', program.float);
|
||||
console.log(' optional: %j', program.optional);
|
||||
program.range = program.range || [];
|
||||
console.log(' range: %j..%j', program.range[0], program.range[1]);
|
||||
console.log(' list: %j', program.list);
|
||||
console.log(' args: %j', program.args);
|
||||
```
|
||||
|
||||
## Custom help
|
||||
|
||||
You can display arbitrary `-h, --help` information
|
||||
by listening for "--help". Commander will automatically
|
||||
exit once you are done so that the remainder of your program
|
||||
does not execute causing undesired behaviours, for example
|
||||
in the following executable "stuff" will not output when
|
||||
`--help` is used.
|
||||
|
||||
```js
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var program = require('../');
|
||||
|
||||
function list(val) {
|
||||
return val.split(',').map(Number);
|
||||
}
|
||||
|
||||
program
|
||||
.version('0.0.1')
|
||||
.option('-f, --foo', 'enable some foo')
|
||||
.option('-b, --bar', 'enable some bar')
|
||||
.option('-B, --baz', 'enable some baz');
|
||||
|
||||
// must be before .parse() since
|
||||
// node's emit() is immediate
|
||||
|
||||
program.on('--help', function(){
|
||||
console.log(' Examples:');
|
||||
console.log('');
|
||||
console.log(' $ custom-help --help');
|
||||
console.log(' $ custom-help -h');
|
||||
console.log('');
|
||||
});
|
||||
|
||||
program.parse(process.argv);
|
||||
|
||||
console.log('stuff');
|
||||
```
|
||||
|
||||
yielding the following help output:
|
||||
|
||||
```
|
||||
|
||||
Usage: custom-help [options]
|
||||
|
||||
Options:
|
||||
|
||||
-h, --help output usage information
|
||||
-V, --version output the version number
|
||||
-f, --foo enable some foo
|
||||
-b, --bar enable some bar
|
||||
-B, --baz enable some baz
|
||||
|
||||
Examples:
|
||||
|
||||
$ custom-help --help
|
||||
$ custom-help -h
|
||||
|
||||
```
|
||||
|
||||
## .outputHelp()
|
||||
|
||||
Output help information without exiting.
|
||||
|
||||
## .help()
|
||||
|
||||
Output help information and exit immediately.
|
||||
|
||||
## Links
|
||||
|
||||
- [API documentation](http://visionmedia.github.com/commander.js/)
|
||||
- [ascii tables](https://github.com/LearnBoost/cli-table)
|
||||
- [progress bars](https://github.com/visionmedia/node-progress)
|
||||
- [more progress bars](https://github.com/substack/node-multimeter)
|
||||
- [examples](https://github.com/visionmedia/commander.js/tree/master/examples)
|
||||
|
||||
## License
|
||||
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>
|
||||
|
||||
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.
|
||||
+847
@@ -0,0 +1,847 @@
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var EventEmitter = require('events').EventEmitter;
|
||||
var spawn = require('child_process').spawn;
|
||||
var fs = require('fs');
|
||||
var exists = fs.existsSync;
|
||||
var path = require('path');
|
||||
var dirname = path.dirname;
|
||||
var basename = path.basename;
|
||||
|
||||
/**
|
||||
* Expose the root command.
|
||||
*/
|
||||
|
||||
exports = module.exports = new Command;
|
||||
|
||||
/**
|
||||
* Expose `Command`.
|
||||
*/
|
||||
|
||||
exports.Command = Command;
|
||||
|
||||
/**
|
||||
* Expose `Option`.
|
||||
*/
|
||||
|
||||
exports.Option = Option;
|
||||
|
||||
/**
|
||||
* Initialize a new `Option` with the given `flags` and `description`.
|
||||
*
|
||||
* @param {String} flags
|
||||
* @param {String} description
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function Option(flags, description) {
|
||||
this.flags = flags;
|
||||
this.required = ~flags.indexOf('<');
|
||||
this.optional = ~flags.indexOf('[');
|
||||
this.bool = !~flags.indexOf('-no-');
|
||||
flags = flags.split(/[ ,|]+/);
|
||||
if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift();
|
||||
this.long = flags.shift();
|
||||
this.description = description || '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Return option name.
|
||||
*
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Option.prototype.name = function(){
|
||||
return this.long
|
||||
.replace('--', '')
|
||||
.replace('no-', '');
|
||||
};
|
||||
|
||||
/**
|
||||
* Check if `arg` matches the short or long flag.
|
||||
*
|
||||
* @param {String} arg
|
||||
* @return {Boolean}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Option.prototype.is = function(arg){
|
||||
return arg == this.short
|
||||
|| arg == this.long;
|
||||
};
|
||||
|
||||
/**
|
||||
* Initialize a new `Command`.
|
||||
*
|
||||
* @param {String} name
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function Command(name) {
|
||||
this.commands = [];
|
||||
this.options = [];
|
||||
this._execs = [];
|
||||
this._args = [];
|
||||
this._name = name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inherit from `EventEmitter.prototype`.
|
||||
*/
|
||||
|
||||
Command.prototype.__proto__ = EventEmitter.prototype;
|
||||
|
||||
/**
|
||||
* Add command `name`.
|
||||
*
|
||||
* The `.action()` callback is invoked when the
|
||||
* command `name` is specified via __ARGV__,
|
||||
* and the remaining arguments are applied to the
|
||||
* function for access.
|
||||
*
|
||||
* When the `name` is "*" an un-matched command
|
||||
* will be passed as the first arg, followed by
|
||||
* the rest of __ARGV__ remaining.
|
||||
*
|
||||
* Examples:
|
||||
*
|
||||
* program
|
||||
* .version('0.0.1')
|
||||
* .option('-C, --chdir <path>', 'change the working directory')
|
||||
* .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')
|
||||
* .option('-T, --no-tests', 'ignore test hook')
|
||||
*
|
||||
* program
|
||||
* .command('setup')
|
||||
* .description('run remote setup commands')
|
||||
* .action(function(){
|
||||
* console.log('setup');
|
||||
* });
|
||||
*
|
||||
* program
|
||||
* .command('exec <cmd>')
|
||||
* .description('run the given remote command')
|
||||
* .action(function(cmd){
|
||||
* console.log('exec "%s"', cmd);
|
||||
* });
|
||||
*
|
||||
* program
|
||||
* .command('*')
|
||||
* .description('deploy the given env')
|
||||
* .action(function(env){
|
||||
* console.log('deploying "%s"', env);
|
||||
* });
|
||||
*
|
||||
* program.parse(process.argv);
|
||||
*
|
||||
* @param {String} name
|
||||
* @param {String} [desc]
|
||||
* @return {Command} the new command
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Command.prototype.command = function(name, desc){
|
||||
var args = name.split(/ +/);
|
||||
var cmd = new Command(args.shift());
|
||||
if (desc) cmd.description(desc);
|
||||
if (desc) this.executables = true;
|
||||
if (desc) this._execs[cmd._name] = true;
|
||||
this.commands.push(cmd);
|
||||
cmd.parseExpectedArgs(args);
|
||||
cmd.parent = this;
|
||||
if (desc) return this;
|
||||
return cmd;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add an implicit `help [cmd]` subcommand
|
||||
* which invokes `--help` for the given command.
|
||||
*
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Command.prototype.addImplicitHelpCommand = function() {
|
||||
this.command('help [cmd]', 'display help for [cmd]');
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse expected `args`.
|
||||
*
|
||||
* For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.
|
||||
*
|
||||
* @param {Array} args
|
||||
* @return {Command} for chaining
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Command.prototype.parseExpectedArgs = function(args){
|
||||
if (!args.length) return;
|
||||
var self = this;
|
||||
args.forEach(function(arg){
|
||||
switch (arg[0]) {
|
||||
case '<':
|
||||
self._args.push({ required: true, name: arg.slice(1, -1) });
|
||||
break;
|
||||
case '[':
|
||||
self._args.push({ required: false, name: arg.slice(1, -1) });
|
||||
break;
|
||||
}
|
||||
});
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Register callback `fn` for the command.
|
||||
*
|
||||
* Examples:
|
||||
*
|
||||
* program
|
||||
* .command('help')
|
||||
* .description('display verbose help')
|
||||
* .action(function(){
|
||||
* // output help here
|
||||
* });
|
||||
*
|
||||
* @param {Function} fn
|
||||
* @return {Command} for chaining
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Command.prototype.action = function(fn){
|
||||
var self = this;
|
||||
this.parent.on(this._name, function(args, unknown){
|
||||
// Parse any so-far unknown options
|
||||
unknown = unknown || [];
|
||||
var parsed = self.parseOptions(unknown);
|
||||
|
||||
// Output help if necessary
|
||||
outputHelpIfNecessary(self, parsed.unknown);
|
||||
|
||||
// If there are still any unknown options, then we simply
|
||||
// die, unless someone asked for help, in which case we give it
|
||||
// to them, and then we die.
|
||||
if (parsed.unknown.length > 0) {
|
||||
self.unknownOption(parsed.unknown[0]);
|
||||
}
|
||||
|
||||
// Leftover arguments need to be pushed back. Fixes issue #56
|
||||
if (parsed.args.length) args = parsed.args.concat(args);
|
||||
|
||||
self._args.forEach(function(arg, i){
|
||||
if (arg.required && null == args[i]) {
|
||||
self.missingArgument(arg.name);
|
||||
}
|
||||
});
|
||||
|
||||
// Always append ourselves to the end of the arguments,
|
||||
// to make sure we match the number of arguments the user
|
||||
// expects
|
||||
if (self._args.length) {
|
||||
args[self._args.length] = self;
|
||||
} else {
|
||||
args.push(self);
|
||||
}
|
||||
|
||||
fn.apply(this, args);
|
||||
});
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Define option with `flags`, `description` and optional
|
||||
* coercion `fn`.
|
||||
*
|
||||
* The `flags` string should contain both the short and long flags,
|
||||
* separated by comma, a pipe or space. The following are all valid
|
||||
* all will output this way when `--help` is used.
|
||||
*
|
||||
* "-p, --pepper"
|
||||
* "-p|--pepper"
|
||||
* "-p --pepper"
|
||||
*
|
||||
* Examples:
|
||||
*
|
||||
* // simple boolean defaulting to false
|
||||
* program.option('-p, --pepper', 'add pepper');
|
||||
*
|
||||
* --pepper
|
||||
* program.pepper
|
||||
* // => Boolean
|
||||
*
|
||||
* // simple boolean defaulting to false
|
||||
* program.option('-C, --no-cheese', 'remove cheese');
|
||||
*
|
||||
* program.cheese
|
||||
* // => true
|
||||
*
|
||||
* --no-cheese
|
||||
* program.cheese
|
||||
* // => true
|
||||
*
|
||||
* // required argument
|
||||
* program.option('-C, --chdir <path>', 'change the working directory');
|
||||
*
|
||||
* --chdir /tmp
|
||||
* program.chdir
|
||||
* // => "/tmp"
|
||||
*
|
||||
* // optional argument
|
||||
* program.option('-c, --cheese [type]', 'add cheese [marble]');
|
||||
*
|
||||
* @param {String} flags
|
||||
* @param {String} description
|
||||
* @param {Function|Mixed} fn or default
|
||||
* @param {Mixed} defaultValue
|
||||
* @return {Command} for chaining
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Command.prototype.option = function(flags, description, fn, defaultValue){
|
||||
var self = this
|
||||
, option = new Option(flags, description)
|
||||
, oname = option.name()
|
||||
, name = camelcase(oname);
|
||||
|
||||
// default as 3rd arg
|
||||
if ('function' != typeof fn) defaultValue = fn, fn = null;
|
||||
|
||||
// preassign default value only for --no-*, [optional], or <required>
|
||||
if (false == option.bool || option.optional || option.required) {
|
||||
// when --no-* we make sure default is true
|
||||
if (false == option.bool) defaultValue = true;
|
||||
// preassign only if we have a default
|
||||
if (undefined !== defaultValue) self[name] = defaultValue;
|
||||
}
|
||||
|
||||
// register the option
|
||||
this.options.push(option);
|
||||
|
||||
// when it's passed assign the value
|
||||
// and conditionally invoke the callback
|
||||
this.on(oname, function(val){
|
||||
// coercion
|
||||
if (null != val && fn) val = fn(val);
|
||||
|
||||
// unassigned or bool
|
||||
if ('boolean' == typeof self[name] || 'undefined' == typeof self[name]) {
|
||||
// if no value, bool true, and we have a default, then use it!
|
||||
if (null == val) {
|
||||
self[name] = option.bool
|
||||
? defaultValue || true
|
||||
: false;
|
||||
} else {
|
||||
self[name] = val;
|
||||
}
|
||||
} else if (null !== val) {
|
||||
// reassign
|
||||
self[name] = val;
|
||||
}
|
||||
});
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse `argv`, settings options and invoking commands when defined.
|
||||
*
|
||||
* @param {Array} argv
|
||||
* @return {Command} for chaining
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Command.prototype.parse = function(argv){
|
||||
// implicit help
|
||||
if (this.executables) this.addImplicitHelpCommand();
|
||||
|
||||
// store raw args
|
||||
this.rawArgs = argv;
|
||||
|
||||
// guess name
|
||||
this._name = this._name || basename(argv[1]);
|
||||
|
||||
// process argv
|
||||
var parsed = this.parseOptions(this.normalize(argv.slice(2)));
|
||||
var args = this.args = parsed.args;
|
||||
|
||||
var result = this.parseArgs(this.args, parsed.unknown);
|
||||
|
||||
// executable sub-commands
|
||||
var name = result.args[0];
|
||||
if (this._execs[name]) return this.executeSubCommand(argv, args, parsed.unknown);
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
/**
|
||||
* Execute a sub-command executable.
|
||||
*
|
||||
* @param {Array} argv
|
||||
* @param {Array} args
|
||||
* @param {Array} unknown
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Command.prototype.executeSubCommand = function(argv, args, unknown) {
|
||||
args = args.concat(unknown);
|
||||
|
||||
if (!args.length) this.help();
|
||||
if ('help' == args[0] && 1 == args.length) this.help();
|
||||
|
||||
// <cmd> --help
|
||||
if ('help' == args[0]) {
|
||||
args[0] = args[1];
|
||||
args[1] = '--help';
|
||||
}
|
||||
|
||||
// executable
|
||||
var dir = dirname(argv[1]);
|
||||
var bin = basename(argv[1]) + '-' + args[0];
|
||||
|
||||
// check for ./<bin> first
|
||||
var local = path.join(dir, bin);
|
||||
|
||||
// run it
|
||||
args = args.slice(1);
|
||||
var proc = spawn(local, args, { stdio: 'inherit', customFds: [0, 1, 2] });
|
||||
proc.on('error', function(err){
|
||||
if (err.code == "ENOENT") {
|
||||
console.error('\n %s(1) does not exist, try --help\n', bin);
|
||||
} else if (err.code == "EACCES") {
|
||||
console.error('\n %s(1) not executable. try chmod or run with root\n', bin);
|
||||
}
|
||||
});
|
||||
|
||||
this.runningCommand = proc;
|
||||
};
|
||||
|
||||
/**
|
||||
* Normalize `args`, splitting joined short flags. For example
|
||||
* the arg "-abc" is equivalent to "-a -b -c".
|
||||
* This also normalizes equal sign and splits "--abc=def" into "--abc def".
|
||||
*
|
||||
* @param {Array} args
|
||||
* @return {Array}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Command.prototype.normalize = function(args){
|
||||
var ret = []
|
||||
, arg
|
||||
, index;
|
||||
|
||||
for (var i = 0, len = args.length; i < len; ++i) {
|
||||
arg = args[i];
|
||||
if (arg.length > 1 && '-' == arg[0] && '-' != arg[1]) {
|
||||
arg.slice(1).split('').forEach(function(c){
|
||||
ret.push('-' + c);
|
||||
});
|
||||
} else if (/^--/.test(arg) && ~(index = arg.indexOf('='))) {
|
||||
ret.push(arg.slice(0, index), arg.slice(index + 1));
|
||||
} else {
|
||||
ret.push(arg);
|
||||
}
|
||||
}
|
||||
|
||||
return ret;
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse command `args`.
|
||||
*
|
||||
* When listener(s) are available those
|
||||
* callbacks are invoked, otherwise the "*"
|
||||
* event is emitted and those actions are invoked.
|
||||
*
|
||||
* @param {Array} args
|
||||
* @return {Command} for chaining
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Command.prototype.parseArgs = function(args, unknown){
|
||||
var cmds = this.commands
|
||||
, len = cmds.length
|
||||
, name;
|
||||
|
||||
if (args.length) {
|
||||
name = args[0];
|
||||
if (this.listeners(name).length) {
|
||||
this.emit(args.shift(), args, unknown);
|
||||
} else {
|
||||
this.emit('*', args);
|
||||
}
|
||||
} else {
|
||||
outputHelpIfNecessary(this, unknown);
|
||||
|
||||
// If there were no args and we have unknown options,
|
||||
// then they are extraneous and we need to error.
|
||||
if (unknown.length > 0) {
|
||||
this.unknownOption(unknown[0]);
|
||||
}
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return an option matching `arg` if any.
|
||||
*
|
||||
* @param {String} arg
|
||||
* @return {Option}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Command.prototype.optionFor = function(arg){
|
||||
for (var i = 0, len = this.options.length; i < len; ++i) {
|
||||
if (this.options[i].is(arg)) {
|
||||
return this.options[i];
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse options from `argv` returning `argv`
|
||||
* void of these options.
|
||||
*
|
||||
* @param {Array} argv
|
||||
* @return {Array}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Command.prototype.parseOptions = function(argv){
|
||||
var args = []
|
||||
, len = argv.length
|
||||
, literal
|
||||
, option
|
||||
, arg;
|
||||
|
||||
var unknownOptions = [];
|
||||
|
||||
// parse options
|
||||
for (var i = 0; i < len; ++i) {
|
||||
arg = argv[i];
|
||||
|
||||
// literal args after --
|
||||
if ('--' == arg) {
|
||||
literal = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (literal) {
|
||||
args.push(arg);
|
||||
continue;
|
||||
}
|
||||
|
||||
// find matching Option
|
||||
option = this.optionFor(arg);
|
||||
|
||||
// option is defined
|
||||
if (option) {
|
||||
// requires arg
|
||||
if (option.required) {
|
||||
arg = argv[++i];
|
||||
if (null == arg) return this.optionMissingArgument(option);
|
||||
if ('-' == arg[0] && '-' != arg) return this.optionMissingArgument(option, arg);
|
||||
this.emit(option.name(), arg);
|
||||
// optional arg
|
||||
} else if (option.optional) {
|
||||
arg = argv[i+1];
|
||||
if (null == arg || ('-' == arg[0] && '-' != arg)) {
|
||||
arg = null;
|
||||
} else {
|
||||
++i;
|
||||
}
|
||||
this.emit(option.name(), arg);
|
||||
// bool
|
||||
} else {
|
||||
this.emit(option.name());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// looks like an option
|
||||
if (arg.length > 1 && '-' == arg[0]) {
|
||||
unknownOptions.push(arg);
|
||||
|
||||
// If the next argument looks like it might be
|
||||
// an argument for this option, we pass it on.
|
||||
// If it isn't, then it'll simply be ignored
|
||||
if (argv[i+1] && '-' != argv[i+1][0]) {
|
||||
unknownOptions.push(argv[++i]);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// arg
|
||||
args.push(arg);
|
||||
}
|
||||
|
||||
return { args: args, unknown: unknownOptions };
|
||||
};
|
||||
|
||||
/**
|
||||
* Argument `name` is missing.
|
||||
*
|
||||
* @param {String} name
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Command.prototype.missingArgument = function(name){
|
||||
console.error();
|
||||
console.error(" error: missing required argument `%s'", name);
|
||||
console.error();
|
||||
process.exit(1);
|
||||
};
|
||||
|
||||
/**
|
||||
* `Option` is missing an argument, but received `flag` or nothing.
|
||||
*
|
||||
* @param {String} option
|
||||
* @param {String} flag
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Command.prototype.optionMissingArgument = function(option, flag){
|
||||
console.error();
|
||||
if (flag) {
|
||||
console.error(" error: option `%s' argument missing, got `%s'", option.flags, flag);
|
||||
} else {
|
||||
console.error(" error: option `%s' argument missing", option.flags);
|
||||
}
|
||||
console.error();
|
||||
process.exit(1);
|
||||
};
|
||||
|
||||
/**
|
||||
* Unknown option `flag`.
|
||||
*
|
||||
* @param {String} flag
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Command.prototype.unknownOption = function(flag){
|
||||
console.error();
|
||||
console.error(" error: unknown option `%s'", flag);
|
||||
console.error();
|
||||
process.exit(1);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Set the program version to `str`.
|
||||
*
|
||||
* This method auto-registers the "-V, --version" flag
|
||||
* which will print the version number when passed.
|
||||
*
|
||||
* @param {String} str
|
||||
* @param {String} flags
|
||||
* @return {Command} for chaining
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Command.prototype.version = function(str, flags){
|
||||
if (0 == arguments.length) return this._version;
|
||||
this._version = str;
|
||||
flags = flags || '-V, --version';
|
||||
this.option(flags, 'output the version number');
|
||||
this.on('version', function(){
|
||||
console.log(str);
|
||||
process.exit(0);
|
||||
});
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Set the description `str`.
|
||||
*
|
||||
* @param {String} str
|
||||
* @return {String|Command}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Command.prototype.description = function(str){
|
||||
if (0 == arguments.length) return this._description;
|
||||
this._description = str;
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Set / get the command usage `str`.
|
||||
*
|
||||
* @param {String} str
|
||||
* @return {String|Command}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Command.prototype.usage = function(str){
|
||||
var args = this._args.map(function(arg){
|
||||
return arg.required
|
||||
? '<' + arg.name + '>'
|
||||
: '[' + arg.name + ']';
|
||||
});
|
||||
|
||||
var usage = '[options'
|
||||
+ (this.commands.length ? '] [command' : '')
|
||||
+ ']'
|
||||
+ (this._args.length ? ' ' + args : '');
|
||||
|
||||
if (0 == arguments.length) return this._usage || usage;
|
||||
this._usage = str;
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the largest option length.
|
||||
*
|
||||
* @return {Number}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Command.prototype.largestOptionLength = function(){
|
||||
return this.options.reduce(function(max, option){
|
||||
return Math.max(max, option.flags.length);
|
||||
}, 0);
|
||||
};
|
||||
|
||||
/**
|
||||
* Return help for options.
|
||||
*
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Command.prototype.optionHelp = function(){
|
||||
var width = this.largestOptionLength();
|
||||
|
||||
// Prepend the help information
|
||||
return [pad('-h, --help', width) + ' ' + 'output usage information']
|
||||
.concat(this.options.map(function(option){
|
||||
return pad(option.flags, width)
|
||||
+ ' ' + option.description;
|
||||
}))
|
||||
.join('\n');
|
||||
};
|
||||
|
||||
/**
|
||||
* Return command help documentation.
|
||||
*
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Command.prototype.commandHelp = function(){
|
||||
if (!this.commands.length) return '';
|
||||
return [
|
||||
''
|
||||
, ' Commands:'
|
||||
, ''
|
||||
, this.commands.map(function(cmd){
|
||||
var args = cmd._args.map(function(arg){
|
||||
return arg.required
|
||||
? '<' + arg.name + '>'
|
||||
: '[' + arg.name + ']';
|
||||
}).join(' ');
|
||||
|
||||
return pad(cmd._name
|
||||
+ (cmd.options.length
|
||||
? ' [options]'
|
||||
: '') + ' ' + args, 22)
|
||||
+ (cmd.description()
|
||||
? ' ' + cmd.description()
|
||||
: '');
|
||||
}).join('\n').replace(/^/gm, ' ')
|
||||
, ''
|
||||
].join('\n');
|
||||
};
|
||||
|
||||
/**
|
||||
* Return program help documentation.
|
||||
*
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
Command.prototype.helpInformation = function(){
|
||||
return [
|
||||
''
|
||||
, ' Usage: ' + this._name + ' ' + this.usage()
|
||||
, '' + this.commandHelp()
|
||||
, ' Options:'
|
||||
, ''
|
||||
, '' + this.optionHelp().replace(/^/gm, ' ')
|
||||
, ''
|
||||
, ''
|
||||
].join('\n');
|
||||
};
|
||||
|
||||
/**
|
||||
* Output help information for this command
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Command.prototype.outputHelp = function(){
|
||||
process.stdout.write(this.helpInformation());
|
||||
this.emit('--help');
|
||||
};
|
||||
|
||||
/**
|
||||
* Output help information and exit.
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
|
||||
Command.prototype.help = function(){
|
||||
this.outputHelp();
|
||||
process.exit();
|
||||
};
|
||||
|
||||
/**
|
||||
* Camel-case the given `flag`
|
||||
*
|
||||
* @param {String} flag
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function camelcase(flag) {
|
||||
return flag.split('-').reduce(function(str, word){
|
||||
return str + word[0].toUpperCase() + word.slice(1);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Pad `str` to `width`.
|
||||
*
|
||||
* @param {String} str
|
||||
* @param {Number} width
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function pad(str, width) {
|
||||
var len = Math.max(0, width - str.length);
|
||||
return str + Array(len + 1).join(' ');
|
||||
}
|
||||
|
||||
/**
|
||||
* Output help information if necessary
|
||||
*
|
||||
* @param {Command} command to output help for
|
||||
* @param {Array} array of options to search for -h or --help
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function outputHelpIfNecessary(cmd, options) {
|
||||
options = options || [];
|
||||
for (var i = 0; i < options.length; i++) {
|
||||
if (options[i] == '--help' || options[i] == '-h') {
|
||||
cmd.outputHelp();
|
||||
process.exit(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"name": "commander",
|
||||
"version": "2.0.0",
|
||||
"description": "the complete solution for node.js command-line programs",
|
||||
"keywords": [
|
||||
"command",
|
||||
"option",
|
||||
"parser",
|
||||
"prompt",
|
||||
"stdin"
|
||||
],
|
||||
"author": {
|
||||
"name": "TJ Holowaychuk",
|
||||
"email": "tj@vision-media.ca"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/visionmedia/commander.js.git"
|
||||
},
|
||||
"devDependencies": {
|
||||
"should": ">= 0.0.1"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "make test"
|
||||
},
|
||||
"main": "index",
|
||||
"engines": {
|
||||
"node": ">= 0.6.x"
|
||||
},
|
||||
"readme": "# Commander.js\n\n The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/visionmedia/commander).\n\n [](http://travis-ci.org/visionmedia/commander.js)\n\n## Installation\n\n $ npm install commander\n\n## Option parsing\n\n Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options.\n\n```js\n#!/usr/bin/env node\n\n/**\n * Module dependencies.\n */\n\nvar program = require('commander');\n\nprogram\n .version('0.0.1')\n .option('-p, --peppers', 'Add peppers')\n .option('-P, --pineapple', 'Add pineapple')\n .option('-b, --bbq', 'Add bbq sauce')\n .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')\n .parse(process.argv);\n\nconsole.log('you ordered a pizza with:');\nif (program.peppers) console.log(' - peppers');\nif (program.pineapple) console.log(' - pineapple');\nif (program.bbq) console.log(' - bbq');\nconsole.log(' - %s cheese', program.cheese);\n```\n\n Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as \"--template-engine\" are camel-cased, becoming `program.templateEngine` etc.\n\n## Automated --help\n\n The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free:\n\n``` \n $ ./examples/pizza --help\n\n Usage: pizza [options]\n\n Options:\n\n -V, --version output the version number\n -p, --peppers Add peppers\n -P, --pineapple Add pineapple\n -b, --bbq Add bbq sauce\n -c, --cheese <type> Add the specified type of cheese [marble]\n -h, --help output usage information\n\n```\n\n## Coercion\n\n```js\nfunction range(val) {\n return val.split('..').map(Number);\n}\n\nfunction list(val) {\n return val.split(',');\n}\n\nprogram\n .version('0.0.1')\n .usage('[options] <file ...>')\n .option('-i, --integer <n>', 'An integer argument', parseInt)\n .option('-f, --float <n>', 'A float argument', parseFloat)\n .option('-r, --range <a>..<b>', 'A range', range)\n .option('-l, --list <items>', 'A list', list)\n .option('-o, --optional [value]', 'An optional value')\n .parse(process.argv);\n\nconsole.log(' int: %j', program.integer);\nconsole.log(' float: %j', program.float);\nconsole.log(' optional: %j', program.optional);\nprogram.range = program.range || [];\nconsole.log(' range: %j..%j', program.range[0], program.range[1]);\nconsole.log(' list: %j', program.list);\nconsole.log(' args: %j', program.args);\n```\n\n## Custom help\n\n You can display arbitrary `-h, --help` information\n by listening for \"--help\". Commander will automatically\n exit once you are done so that the remainder of your program\n does not execute causing undesired behaviours, for example\n in the following executable \"stuff\" will not output when\n `--help` is used.\n\n```js\n#!/usr/bin/env node\n\n/**\n * Module dependencies.\n */\n\nvar program = require('../');\n\nfunction list(val) {\n return val.split(',').map(Number);\n}\n\nprogram\n .version('0.0.1')\n .option('-f, --foo', 'enable some foo')\n .option('-b, --bar', 'enable some bar')\n .option('-B, --baz', 'enable some baz');\n\n// must be before .parse() since\n// node's emit() is immediate\n\nprogram.on('--help', function(){\n console.log(' Examples:');\n console.log('');\n console.log(' $ custom-help --help');\n console.log(' $ custom-help -h');\n console.log('');\n});\n\nprogram.parse(process.argv);\n\nconsole.log('stuff');\n```\n\nyielding the following help output:\n\n```\n\nUsage: custom-help [options]\n\nOptions:\n\n -h, --help output usage information\n -V, --version output the version number\n -f, --foo enable some foo\n -b, --bar enable some bar\n -B, --baz enable some baz\n\nExamples:\n\n $ custom-help --help\n $ custom-help -h\n\n```\n\n## .outputHelp()\n\n Output help information without exiting.\n\n## .help()\n\n Output help information and exit immediately.\n\n## Links\n\n - [API documentation](http://visionmedia.github.com/commander.js/)\n - [ascii tables](https://github.com/LearnBoost/cli-table)\n - [progress bars](https://github.com/visionmedia/node-progress)\n - [more progress bars](https://github.com/substack/node-multimeter)\n - [examples](https://github.com/visionmedia/commander.js/tree/master/examples)\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software withLine truncated
|
||||
"readmeFilename": "Readme.md",
|
||||
"bugs": {
|
||||
"url": "https://github.com/visionmedia/commander.js/issues"
|
||||
},
|
||||
"homepage": "https://github.com/visionmedia/commander.js",
|
||||
"_id": "commander@2.0.0",
|
||||
"_from": "commander@2.0.0"
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
# debug
|
||||
|
||||
tiny node.js debugging utility modelled after node core's debugging technique.
|
||||
|
||||
## Installation
|
||||
|
||||
```
|
||||
$ npm install debug
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
With `debug` you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated `console.error`, so all of the `console` format string goodies you're used to work fine. A unique color is selected per-function for visibility.
|
||||
|
||||
Example _app.js_:
|
||||
|
||||
```js
|
||||
var debug = require('debug')('http')
|
||||
, http = require('http')
|
||||
, name = 'My App';
|
||||
|
||||
// fake app
|
||||
|
||||
debug('booting %s', name);
|
||||
|
||||
http.createServer(function(req, res){
|
||||
debug(req.method + ' ' + req.url);
|
||||
res.end('hello\n');
|
||||
}).listen(3000, function(){
|
||||
debug('listening');
|
||||
});
|
||||
|
||||
// fake worker of some kind
|
||||
|
||||
require('./worker');
|
||||
```
|
||||
|
||||
Example _worker.js_:
|
||||
|
||||
```js
|
||||
var debug = require('debug')('worker');
|
||||
|
||||
setInterval(function(){
|
||||
debug('doing some work');
|
||||
}, 1000);
|
||||
```
|
||||
|
||||
The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples:
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
## Millisecond diff
|
||||
|
||||
When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls.
|
||||
|
||||

|
||||
|
||||
When stderr is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below:
|
||||
_(NOTE: Debug now uses stderr instead of stdout, so the correct shell command for this example is actually `DEBUG=* node example/worker 2> out &`)_
|
||||
|
||||

|
||||
|
||||
## Conventions
|
||||
|
||||
If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser".
|
||||
|
||||
## Wildcards
|
||||
|
||||
The "*" character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect.compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`.
|
||||
|
||||
You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=* -connect:*` would include all debuggers except those starting with "connect:".
|
||||
|
||||
## Browser support
|
||||
|
||||
Debug works in the browser as well, currently persisted by `localStorage`. For example if you have `worker:a` and `worker:b` as shown below, and wish to debug both type `debug.enable('worker:*')` in the console and refresh the page, this will remain until you disable with `debug.disable()`.
|
||||
|
||||
```js
|
||||
a = debug('worker:a');
|
||||
b = debug('worker:b');
|
||||
|
||||
setInterval(function(){
|
||||
a('doing some work');
|
||||
}, 1000);
|
||||
|
||||
setInterval(function(){
|
||||
a('doing some work');
|
||||
}, 1200);
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>
|
||||
|
||||
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.
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
|
||||
/**
|
||||
* Expose `debug()` as the module.
|
||||
*/
|
||||
|
||||
module.exports = debug;
|
||||
|
||||
/**
|
||||
* Create a debugger with the given `name`.
|
||||
*
|
||||
* @param {String} name
|
||||
* @return {Type}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function debug(name) {
|
||||
if (!debug.enabled(name)) return function(){};
|
||||
|
||||
return function(fmt){
|
||||
fmt = coerce(fmt);
|
||||
|
||||
var curr = new Date;
|
||||
var ms = curr - (debug[name] || curr);
|
||||
debug[name] = curr;
|
||||
|
||||
fmt = name
|
||||
+ ' '
|
||||
+ fmt
|
||||
+ ' +' + debug.humanize(ms);
|
||||
|
||||
// This hackery is required for IE8
|
||||
// where `console.log` doesn't have 'apply'
|
||||
window.console
|
||||
&& console.log
|
||||
&& Function.prototype.apply.call(console.log, console, arguments);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The currently active debug mode names.
|
||||
*/
|
||||
|
||||
debug.names = [];
|
||||
debug.skips = [];
|
||||
|
||||
/**
|
||||
* Enables a debug mode by name. This can include modes
|
||||
* separated by a colon and wildcards.
|
||||
*
|
||||
* @param {String} name
|
||||
* @api public
|
||||
*/
|
||||
|
||||
debug.enable = function(name) {
|
||||
try {
|
||||
localStorage.debug = name;
|
||||
} catch(e){}
|
||||
|
||||
var split = (name || '').split(/[\s,]+/)
|
||||
, len = split.length;
|
||||
|
||||
for (var i = 0; i < len; i++) {
|
||||
name = split[i].replace('*', '.*?');
|
||||
if (name[0] === '-') {
|
||||
debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
|
||||
}
|
||||
else {
|
||||
debug.names.push(new RegExp('^' + name + '$'));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Disable debug output.
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
|
||||
debug.disable = function(){
|
||||
debug.enable('');
|
||||
};
|
||||
|
||||
/**
|
||||
* Humanize the given `ms`.
|
||||
*
|
||||
* @param {Number} m
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
debug.humanize = function(ms) {
|
||||
var sec = 1000
|
||||
, min = 60 * 1000
|
||||
, hour = 60 * min;
|
||||
|
||||
if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
|
||||
if (ms >= min) return (ms / min).toFixed(1) + 'm';
|
||||
if (ms >= sec) return (ms / sec | 0) + 's';
|
||||
return ms + 'ms';
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns true if the given mode name is enabled, false otherwise.
|
||||
*
|
||||
* @param {String} name
|
||||
* @return {Boolean}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
debug.enabled = function(name) {
|
||||
for (var i = 0, len = debug.skips.length; i < len; i++) {
|
||||
if (debug.skips[i].test(name)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
for (var i = 0, len = debug.names.length; i < len; i++) {
|
||||
if (debug.names[i].test(name)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Coerce `val`.
|
||||
*/
|
||||
|
||||
function coerce(val) {
|
||||
if (val instanceof Error) return val.stack || val.message;
|
||||
return val;
|
||||
}
|
||||
|
||||
// persist
|
||||
|
||||
try {
|
||||
if (window.localStorage) debug.enable(localStorage.debug);
|
||||
} catch(e){}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
if ('undefined' == typeof window) {
|
||||
module.exports = require('./lib/debug');
|
||||
} else {
|
||||
module.exports = require('./debug');
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var tty = require('tty');
|
||||
|
||||
/**
|
||||
* Expose `debug()` as the module.
|
||||
*/
|
||||
|
||||
module.exports = debug;
|
||||
|
||||
/**
|
||||
* Enabled debuggers.
|
||||
*/
|
||||
|
||||
var names = []
|
||||
, skips = [];
|
||||
|
||||
(process.env.DEBUG || '')
|
||||
.split(/[\s,]+/)
|
||||
.forEach(function(name){
|
||||
name = name.replace('*', '.*?');
|
||||
if (name[0] === '-') {
|
||||
skips.push(new RegExp('^' + name.substr(1) + '$'));
|
||||
} else {
|
||||
names.push(new RegExp('^' + name + '$'));
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Colors.
|
||||
*/
|
||||
|
||||
var colors = [6, 2, 3, 4, 5, 1];
|
||||
|
||||
/**
|
||||
* Previous debug() call.
|
||||
*/
|
||||
|
||||
var prev = {};
|
||||
|
||||
/**
|
||||
* Previously assigned color.
|
||||
*/
|
||||
|
||||
var prevColor = 0;
|
||||
|
||||
/**
|
||||
* Is stdout a TTY? Colored output is disabled when `true`.
|
||||
*/
|
||||
|
||||
var isatty = tty.isatty(2);
|
||||
|
||||
/**
|
||||
* Select a color.
|
||||
*
|
||||
* @return {Number}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function color() {
|
||||
return colors[prevColor++ % colors.length];
|
||||
}
|
||||
|
||||
/**
|
||||
* Humanize the given `ms`.
|
||||
*
|
||||
* @param {Number} m
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function humanize(ms) {
|
||||
var sec = 1000
|
||||
, min = 60 * 1000
|
||||
, hour = 60 * min;
|
||||
|
||||
if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
|
||||
if (ms >= min) return (ms / min).toFixed(1) + 'm';
|
||||
if (ms >= sec) return (ms / sec | 0) + 's';
|
||||
return ms + 'ms';
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a debugger with the given `name`.
|
||||
*
|
||||
* @param {String} name
|
||||
* @return {Type}
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function debug(name) {
|
||||
function disabled(){}
|
||||
disabled.enabled = false;
|
||||
|
||||
var match = skips.some(function(re){
|
||||
return re.test(name);
|
||||
});
|
||||
|
||||
if (match) return disabled;
|
||||
|
||||
match = names.some(function(re){
|
||||
return re.test(name);
|
||||
});
|
||||
|
||||
if (!match) return disabled;
|
||||
var c = color();
|
||||
|
||||
function colored(fmt) {
|
||||
fmt = coerce(fmt);
|
||||
|
||||
var curr = new Date;
|
||||
var ms = curr - (prev[name] || curr);
|
||||
prev[name] = curr;
|
||||
|
||||
fmt = ' \u001b[9' + c + 'm' + name + ' '
|
||||
+ '\u001b[3' + c + 'm\u001b[90m'
|
||||
+ fmt + '\u001b[3' + c + 'm'
|
||||
+ ' +' + humanize(ms) + '\u001b[0m';
|
||||
|
||||
console.error.apply(this, arguments);
|
||||
}
|
||||
|
||||
function plain(fmt) {
|
||||
fmt = coerce(fmt);
|
||||
|
||||
fmt = new Date().toUTCString()
|
||||
+ ' ' + name + ' ' + fmt;
|
||||
console.error.apply(this, arguments);
|
||||
}
|
||||
|
||||
colored.enabled = plain.enabled = true;
|
||||
|
||||
return isatty || process.env.DEBUG_COLORS
|
||||
? colored
|
||||
: plain;
|
||||
}
|
||||
|
||||
/**
|
||||
* Coerce `val`.
|
||||
*/
|
||||
|
||||
function coerce(val) {
|
||||
if (val instanceof Error) return val.stack || val.message;
|
||||
return val;
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"name": "debug",
|
||||
"version": "0.7.4",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/visionmedia/debug.git"
|
||||
},
|
||||
"description": "small debugging utility",
|
||||
"keywords": [
|
||||
"debug",
|
||||
"log",
|
||||
"debugger"
|
||||
],
|
||||
"author": {
|
||||
"name": "TJ Holowaychuk",
|
||||
"email": "tj@vision-media.ca"
|
||||
},
|
||||
"dependencies": {},
|
||||
"devDependencies": {
|
||||
"mocha": "*"
|
||||
},
|
||||
"main": "lib/debug.js",
|
||||
"browser": "./debug.js",
|
||||
"engines": {
|
||||
"node": "*"
|
||||
},
|
||||
"files": [
|
||||
"lib/debug.js",
|
||||
"debug.js",
|
||||
"index.js"
|
||||
],
|
||||
"component": {
|
||||
"scripts": {
|
||||
"debug/index.js": "index.js",
|
||||
"debug/debug.js": "debug.js"
|
||||
}
|
||||
},
|
||||
"readme": "# debug\n\n tiny node.js debugging utility modelled after node core's debugging technique.\n\n## Installation\n\n```\n$ npm install debug\n```\n\n## Usage\n\n With `debug` you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated `console.error`, so all of the `console` format string goodies you're used to work fine. A unique color is selected per-function for visibility.\n \nExample _app.js_:\n\n```js\nvar debug = require('debug')('http')\n , http = require('http')\n , name = 'My App';\n\n// fake app\n\ndebug('booting %s', name);\n\nhttp.createServer(function(req, res){\n debug(req.method + ' ' + req.url);\n res.end('hello\\n');\n}).listen(3000, function(){\n debug('listening');\n});\n\n// fake worker of some kind\n\nrequire('./worker');\n```\n\nExample _worker.js_:\n\n```js\nvar debug = require('debug')('worker');\n\nsetInterval(function(){\n debug('doing some work');\n}, 1000);\n```\n\n The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples:\n\n \n\n \n\n## Millisecond diff\n\n When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the \"+NNNms\" will show you how much time was spent between calls.\n\n \n\n When stderr is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below:\n _(NOTE: Debug now uses stderr instead of stdout, so the correct shell command for this example is actually `DEBUG=* node example/worker 2> out &`)_\n \n \n \n## Conventions\n\n If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use \":\" to separate features. For example \"bodyParser\" from Connect would then be \"connect:bodyParser\". \n\n## Wildcards\n\n The \"*\" character may be used as a wildcard. Suppose for example your library has debuggers named \"connect:bodyParser\", \"connect:compress\", \"connect:session\", instead of listing all three with `DEBUG=connect:bodyParser,connect.compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`.\n\n You can also exclude specific debuggers by prefixing them with a \"-\" character. For example, `DEBUG=* -connect:*` would include all debuggers except those starting with \"connect:\".\n\n## Browser support\n\n Debug works in the browser as well, currently persisted by `localStorage`. For example if you have `worker:a` and `worker:b` as shown below, and wish to debug both type `debug.enable('worker:*')` in the console and refresh the page, this will remain until you disable with `debug.disable()`. \n\n```js\na = debug('worker:a');\nb = debug('worker:b');\n\nsetInterval(function(){\n a('doing some work');\n}, 1000);\n\nsetInterval(function(){\n a('doing some work');\n}, 1200);\n```\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n",
|
||||
"readmeFilename": "Readme.md",
|
||||
"bugs": {
|
||||
"url": "https://github.com/visionmedia/debug/issues"
|
||||
},
|
||||
"homepage": "https://github.com/visionmedia/debug",
|
||||
"_id": "debug@0.7.4",
|
||||
"_from": "debug@*"
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
# jsdiff
|
||||
|
||||
[](http://travis-ci.org/kpdecker/jsdiff)
|
||||
|
||||
A javascript text differencing implementation.
|
||||
|
||||
Based on the algorithm proposed in
|
||||
["An O(ND) Difference Algorithm and its Variations" (Myers, 1986)](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927).
|
||||
|
||||
## Installation
|
||||
|
||||
npm install diff
|
||||
|
||||
or
|
||||
|
||||
git clone git://github.com/kpdecker/jsdiff.git
|
||||
|
||||
## API
|
||||
|
||||
* JsDiff.diffChars(oldStr, newStr)
|
||||
Diffs two blocks of text, comparing character by character.
|
||||
|
||||
Returns a list of change objects (See below).
|
||||
|
||||
* JsDiff.diffWords(oldStr, newStr)
|
||||
Diffs two blocks of text, comparing word by word.
|
||||
|
||||
Returns a list of change objects (See below).
|
||||
|
||||
* JsDiff.diffLines(oldStr, newStr)
|
||||
Diffs two blocks of text, comparing line by line.
|
||||
|
||||
Returns a list of change objects (See below).
|
||||
|
||||
* JsDiff.diffCss(oldStr, newStr)
|
||||
Diffs two blocks of text, comparing CSS tokens.
|
||||
|
||||
Returns a list of change objects (See below).
|
||||
|
||||
* JsDiff.createPatch(fileName, oldStr, newStr, oldHeader, newHeader)
|
||||
Creates a unified diff patch.
|
||||
|
||||
Parameters:
|
||||
* fileName : String to be output in the filename sections of the patch
|
||||
* oldStr : Original string value
|
||||
* newStr : New string value
|
||||
* oldHeader : Additional information to include in the old file header
|
||||
* newHeader : Additional information to include in thew new file header
|
||||
|
||||
* JsDiff.applyPatch(oldStr, diffStr)
|
||||
Applies a unified diff patch.
|
||||
|
||||
Return a string containing new version of provided data.
|
||||
|
||||
* convertChangesToXML(changes)
|
||||
Converts a list of changes to a serialized XML format
|
||||
|
||||
### Change Objects
|
||||
Many of the methods above return change objects. These objects are consist of the following fields:
|
||||
|
||||
* value: Text content
|
||||
* added: True if the value was inserted into the new string
|
||||
* removed: True of the value was removed from the old string
|
||||
|
||||
Note that some cases may omit a particular flag field. Comparison on the flag fields should always be done in a truthy or falsy manner.
|
||||
|
||||
## [Example](http://kpdecker.github.com/jsdiff)
|
||||
|
||||
## License
|
||||
|
||||
Software License Agreement (BSD License)
|
||||
|
||||
Copyright (c) 2009-2011, Kevin Decker kpdecker@gmail.com
|
||||
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use of this software in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above
|
||||
copyright notice, this list of conditions and the
|
||||
following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the
|
||||
following disclaimer in the documentation and/or other
|
||||
materials provided with the distribution.
|
||||
|
||||
* Neither the name of Kevin Decker nor the names of its
|
||||
contributors may be used to endorse or promote products
|
||||
derived from this software without specific prior
|
||||
written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
|
||||
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
|
||||
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
|
||||
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
+354
@@ -0,0 +1,354 @@
|
||||
/* See LICENSE file for terms of use */
|
||||
|
||||
/*
|
||||
* Text diff implementation.
|
||||
*
|
||||
* This library supports the following APIS:
|
||||
* JsDiff.diffChars: Character by character diff
|
||||
* JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
|
||||
* JsDiff.diffLines: Line based diff
|
||||
*
|
||||
* JsDiff.diffCss: Diff targeted at CSS content
|
||||
*
|
||||
* These methods are based on the implementation proposed in
|
||||
* "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
|
||||
* http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
|
||||
*/
|
||||
var JsDiff = (function() {
|
||||
/*jshint maxparams: 5*/
|
||||
function clonePath(path) {
|
||||
return { newPos: path.newPos, components: path.components.slice(0) };
|
||||
}
|
||||
function removeEmpty(array) {
|
||||
var ret = [];
|
||||
for (var i = 0; i < array.length; i++) {
|
||||
if (array[i]) {
|
||||
ret.push(array[i]);
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
function escapeHTML(s) {
|
||||
var n = s;
|
||||
n = n.replace(/&/g, '&');
|
||||
n = n.replace(/</g, '<');
|
||||
n = n.replace(/>/g, '>');
|
||||
n = n.replace(/"/g, '"');
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
var Diff = function(ignoreWhitespace) {
|
||||
this.ignoreWhitespace = ignoreWhitespace;
|
||||
};
|
||||
Diff.prototype = {
|
||||
diff: function(oldString, newString) {
|
||||
// Handle the identity case (this is due to unrolling editLength == 0
|
||||
if (newString === oldString) {
|
||||
return [{ value: newString }];
|
||||
}
|
||||
if (!newString) {
|
||||
return [{ value: oldString, removed: true }];
|
||||
}
|
||||
if (!oldString) {
|
||||
return [{ value: newString, added: true }];
|
||||
}
|
||||
|
||||
newString = this.tokenize(newString);
|
||||
oldString = this.tokenize(oldString);
|
||||
|
||||
var newLen = newString.length, oldLen = oldString.length;
|
||||
var maxEditLength = newLen + oldLen;
|
||||
var bestPath = [{ newPos: -1, components: [] }];
|
||||
|
||||
// Seed editLength = 0
|
||||
var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
|
||||
if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) {
|
||||
return bestPath[0].components;
|
||||
}
|
||||
|
||||
for (var editLength = 1; editLength <= maxEditLength; editLength++) {
|
||||
for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) {
|
||||
var basePath;
|
||||
var addPath = bestPath[diagonalPath-1],
|
||||
removePath = bestPath[diagonalPath+1];
|
||||
oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
|
||||
if (addPath) {
|
||||
// No one else is going to attempt to use this value, clear it
|
||||
bestPath[diagonalPath-1] = undefined;
|
||||
}
|
||||
|
||||
var canAdd = addPath && addPath.newPos+1 < newLen;
|
||||
var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
|
||||
if (!canAdd && !canRemove) {
|
||||
bestPath[diagonalPath] = undefined;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Select the diagonal that we want to branch from. We select the prior
|
||||
// path whose position in the new string is the farthest from the origin
|
||||
// and does not pass the bounds of the diff graph
|
||||
if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
|
||||
basePath = clonePath(removePath);
|
||||
this.pushComponent(basePath.components, oldString[oldPos], undefined, true);
|
||||
} else {
|
||||
basePath = clonePath(addPath);
|
||||
basePath.newPos++;
|
||||
this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined);
|
||||
}
|
||||
|
||||
var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath);
|
||||
|
||||
if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) {
|
||||
return basePath.components;
|
||||
} else {
|
||||
bestPath[diagonalPath] = basePath;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
pushComponent: function(components, value, added, removed) {
|
||||
var last = components[components.length-1];
|
||||
if (last && last.added === added && last.removed === removed) {
|
||||
// We need to clone here as the component clone operation is just
|
||||
// as shallow array clone
|
||||
components[components.length-1] =
|
||||
{value: this.join(last.value, value), added: added, removed: removed };
|
||||
} else {
|
||||
components.push({value: value, added: added, removed: removed });
|
||||
}
|
||||
},
|
||||
extractCommon: function(basePath, newString, oldString, diagonalPath) {
|
||||
var newLen = newString.length,
|
||||
oldLen = oldString.length,
|
||||
newPos = basePath.newPos,
|
||||
oldPos = newPos - diagonalPath;
|
||||
while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) {
|
||||
newPos++;
|
||||
oldPos++;
|
||||
|
||||
this.pushComponent(basePath.components, newString[newPos], undefined, undefined);
|
||||
}
|
||||
basePath.newPos = newPos;
|
||||
return oldPos;
|
||||
},
|
||||
|
||||
equals: function(left, right) {
|
||||
var reWhitespace = /\S/;
|
||||
if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) {
|
||||
return true;
|
||||
} else {
|
||||
return left === right;
|
||||
}
|
||||
},
|
||||
join: function(left, right) {
|
||||
return left + right;
|
||||
},
|
||||
tokenize: function(value) {
|
||||
return value;
|
||||
}
|
||||
};
|
||||
|
||||
var CharDiff = new Diff();
|
||||
|
||||
var WordDiff = new Diff(true);
|
||||
var WordWithSpaceDiff = new Diff();
|
||||
WordDiff.tokenize = WordWithSpaceDiff.tokenize = function(value) {
|
||||
return removeEmpty(value.split(/(\s+|\b)/));
|
||||
};
|
||||
|
||||
var CssDiff = new Diff(true);
|
||||
CssDiff.tokenize = function(value) {
|
||||
return removeEmpty(value.split(/([{}:;,]|\s+)/));
|
||||
};
|
||||
|
||||
var LineDiff = new Diff();
|
||||
LineDiff.tokenize = function(value) {
|
||||
return value.split(/^/m);
|
||||
};
|
||||
|
||||
return {
|
||||
Diff: Diff,
|
||||
|
||||
diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); },
|
||||
diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); },
|
||||
diffWordsWithSpace: function(oldStr, newStr) { return WordWithSpaceDiff.diff(oldStr, newStr); },
|
||||
diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); },
|
||||
|
||||
diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); },
|
||||
|
||||
createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) {
|
||||
var ret = [];
|
||||
|
||||
ret.push('Index: ' + fileName);
|
||||
ret.push('===================================================================');
|
||||
ret.push('--- ' + fileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader));
|
||||
ret.push('+++ ' + fileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader));
|
||||
|
||||
var diff = LineDiff.diff(oldStr, newStr);
|
||||
if (!diff[diff.length-1].value) {
|
||||
diff.pop(); // Remove trailing newline add
|
||||
}
|
||||
diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier
|
||||
|
||||
function contextLines(lines) {
|
||||
return lines.map(function(entry) { return ' ' + entry; });
|
||||
}
|
||||
function eofNL(curRange, i, current) {
|
||||
var last = diff[diff.length-2],
|
||||
isLast = i === diff.length-2,
|
||||
isLastOfType = i === diff.length-3 && (current.added !== last.added || current.removed !== last.removed);
|
||||
|
||||
// Figure out if this is the last line for the given file and missing NL
|
||||
if (!/\n$/.test(current.value) && (isLast || isLastOfType)) {
|
||||
curRange.push('\\ No newline at end of file');
|
||||
}
|
||||
}
|
||||
|
||||
var oldRangeStart = 0, newRangeStart = 0, curRange = [],
|
||||
oldLine = 1, newLine = 1;
|
||||
for (var i = 0; i < diff.length; i++) {
|
||||
var current = diff[i],
|
||||
lines = current.lines || current.value.replace(/\n$/, '').split('\n');
|
||||
current.lines = lines;
|
||||
|
||||
if (current.added || current.removed) {
|
||||
if (!oldRangeStart) {
|
||||
var prev = diff[i-1];
|
||||
oldRangeStart = oldLine;
|
||||
newRangeStart = newLine;
|
||||
|
||||
if (prev) {
|
||||
curRange = contextLines(prev.lines.slice(-4));
|
||||
oldRangeStart -= curRange.length;
|
||||
newRangeStart -= curRange.length;
|
||||
}
|
||||
}
|
||||
curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?'+':'-') + entry; }));
|
||||
eofNL(curRange, i, current);
|
||||
|
||||
if (current.added) {
|
||||
newLine += lines.length;
|
||||
} else {
|
||||
oldLine += lines.length;
|
||||
}
|
||||
} else {
|
||||
if (oldRangeStart) {
|
||||
// Close out any changes that have been output (or join overlapping)
|
||||
if (lines.length <= 8 && i < diff.length-2) {
|
||||
// Overlapping
|
||||
curRange.push.apply(curRange, contextLines(lines));
|
||||
} else {
|
||||
// end the range and output
|
||||
var contextSize = Math.min(lines.length, 4);
|
||||
ret.push(
|
||||
'@@ -' + oldRangeStart + ',' + (oldLine-oldRangeStart+contextSize)
|
||||
+ ' +' + newRangeStart + ',' + (newLine-newRangeStart+contextSize)
|
||||
+ ' @@');
|
||||
ret.push.apply(ret, curRange);
|
||||
ret.push.apply(ret, contextLines(lines.slice(0, contextSize)));
|
||||
if (lines.length <= 4) {
|
||||
eofNL(ret, i, current);
|
||||
}
|
||||
|
||||
oldRangeStart = 0; newRangeStart = 0; curRange = [];
|
||||
}
|
||||
}
|
||||
oldLine += lines.length;
|
||||
newLine += lines.length;
|
||||
}
|
||||
}
|
||||
|
||||
return ret.join('\n') + '\n';
|
||||
},
|
||||
|
||||
applyPatch: function(oldStr, uniDiff) {
|
||||
var diffstr = uniDiff.split('\n');
|
||||
var diff = [];
|
||||
var remEOFNL = false,
|
||||
addEOFNL = false;
|
||||
|
||||
for (var i = (diffstr[0][0]==='I'?4:0); i < diffstr.length; i++) {
|
||||
if(diffstr[i][0] === '@') {
|
||||
var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/);
|
||||
diff.unshift({
|
||||
start:meh[3],
|
||||
oldlength:meh[2],
|
||||
oldlines:[],
|
||||
newlength:meh[4],
|
||||
newlines:[]
|
||||
});
|
||||
} else if(diffstr[i][0] === '+') {
|
||||
diff[0].newlines.push(diffstr[i].substr(1));
|
||||
} else if(diffstr[i][0] === '-') {
|
||||
diff[0].oldlines.push(diffstr[i].substr(1));
|
||||
} else if(diffstr[i][0] === ' ') {
|
||||
diff[0].newlines.push(diffstr[i].substr(1));
|
||||
diff[0].oldlines.push(diffstr[i].substr(1));
|
||||
} else if(diffstr[i][0] === '\\') {
|
||||
if (diffstr[i-1][0] === '+') {
|
||||
remEOFNL = true;
|
||||
} else if(diffstr[i-1][0] === '-') {
|
||||
addEOFNL = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var str = oldStr.split('\n');
|
||||
for (var i = diff.length - 1; i >= 0; i--) {
|
||||
var d = diff[i];
|
||||
for (var j = 0; j < d.oldlength; j++) {
|
||||
if(str[d.start-1+j] !== d.oldlines[j]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines));
|
||||
}
|
||||
|
||||
if (remEOFNL) {
|
||||
while (!str[str.length-1]) {
|
||||
str.pop();
|
||||
}
|
||||
} else if (addEOFNL) {
|
||||
str.push('');
|
||||
}
|
||||
return str.join('\n');
|
||||
},
|
||||
|
||||
convertChangesToXML: function(changes){
|
||||
var ret = [];
|
||||
for ( var i = 0; i < changes.length; i++) {
|
||||
var change = changes[i];
|
||||
if (change.added) {
|
||||
ret.push('<ins>');
|
||||
} else if (change.removed) {
|
||||
ret.push('<del>');
|
||||
}
|
||||
|
||||
ret.push(escapeHTML(change.value));
|
||||
|
||||
if (change.added) {
|
||||
ret.push('</ins>');
|
||||
} else if (change.removed) {
|
||||
ret.push('</del>');
|
||||
}
|
||||
}
|
||||
return ret.join('');
|
||||
},
|
||||
|
||||
// See: http://code.google.com/p/google-diff-match-patch/wiki/API
|
||||
convertChangesToDMP: function(changes){
|
||||
var ret = [], change;
|
||||
for ( var i = 0; i < changes.length; i++) {
|
||||
change = changes[i];
|
||||
ret.push([(change.added ? 1 : change.removed ? -1 : 0), change.value]);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
};
|
||||
})();
|
||||
|
||||
if (typeof module !== 'undefined') {
|
||||
module.exports = JsDiff;
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"name": "diff",
|
||||
"version": "1.0.7",
|
||||
"description": "A javascript text diff implementation.",
|
||||
"keywords": [
|
||||
"diff",
|
||||
"javascript"
|
||||
],
|
||||
"maintainers": [
|
||||
{
|
||||
"name": "Kevin Decker",
|
||||
"email": "kpdecker@gmail.com",
|
||||
"url": "http://incaseofstairs.com"
|
||||
}
|
||||
],
|
||||
"bugs": {
|
||||
"url": "http://github.com/kpdecker/jsdiff/issues",
|
||||
"email": "kpdecker@gmail.com"
|
||||
},
|
||||
"licenses": [
|
||||
{
|
||||
"type": "BSD",
|
||||
"url": "http://github.com/kpdecker/jsdiff/blob/master/LICENSE"
|
||||
}
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/kpdecker/jsdiff.git"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.3.1"
|
||||
},
|
||||
"main": "./diff",
|
||||
"scripts": {
|
||||
"test": "mocha test/*.js"
|
||||
},
|
||||
"dependencies": {},
|
||||
"devDependencies": {
|
||||
"mocha": "~1.6",
|
||||
"should": "~1.2"
|
||||
},
|
||||
"optionalDependencies": {},
|
||||
"files": [
|
||||
"diff.js"
|
||||
],
|
||||
"readme": "# jsdiff\n\n[](http://travis-ci.org/kpdecker/jsdiff)\n\nA javascript text differencing implementation.\n\nBased on the algorithm proposed in\n[\"An O(ND) Difference Algorithm and its Variations\" (Myers, 1986)](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927).\n\n## Installation\n\n npm install diff\n\nor\n\n git clone git://github.com/kpdecker/jsdiff.git\n\n## API\n\n* JsDiff.diffChars(oldStr, newStr)\n Diffs two blocks of text, comparing character by character.\n\n Returns a list of change objects (See below).\n\n* JsDiff.diffWords(oldStr, newStr)\n Diffs two blocks of text, comparing word by word.\n\n Returns a list of change objects (See below).\n\n* JsDiff.diffLines(oldStr, newStr)\n Diffs two blocks of text, comparing line by line.\n\n Returns a list of change objects (See below).\n\n* JsDiff.diffCss(oldStr, newStr)\n Diffs two blocks of text, comparing CSS tokens.\n\n Returns a list of change objects (See below).\n\n* JsDiff.createPatch(fileName, oldStr, newStr, oldHeader, newHeader)\n Creates a unified diff patch.\n\n Parameters:\n * fileName : String to be output in the filename sections of the patch\n * oldStr : Original string value\n * newStr : New string value\n * oldHeader : Additional information to include in the old file header\n * newHeader : Additional information to include in thew new file header\n\n* JsDiff.applyPatch(oldStr, diffStr)\n Applies a unified diff patch.\n\n Return a string containing new version of provided data.\n\n* convertChangesToXML(changes)\n Converts a list of changes to a serialized XML format\n\n### Change Objects\nMany of the methods above return change objects. These objects are consist of the following fields:\n\n* value: Text content\n* added: True if the value was inserted into the new string\n* removed: True of the value was removed from the old string\n\nNote that some cases may omit a particular flag field. Comparison on the flag fields should always be done in a truthy or falsy manner.\n\n## [Example](http://kpdecker.github.com/jsdiff)\n\n## License\n\nSoftware License Agreement (BSD License)\n\nCopyright (c) 2009-2011, Kevin Decker kpdecker@gmail.com\n\nAll rights reserved.\n\nRedistribution and use of this software in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above\n copyright notice, this list of conditions and the\n following disclaimer.\n\n* Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the\n following disclaimer in the documentation and/or other\n materials provided with the distribution.\n\n* Neither the name of Kevin Decker nor the names of its\n contributors may be used to endorse or promote products\n derived from this software without specific prior\n written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR\nIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\nIN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\nOF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n",
|
||||
"readmeFilename": "README.md",
|
||||
"homepage": "https://github.com/kpdecker/jsdiff",
|
||||
"_id": "diff@1.0.7",
|
||||
"_from": "diff@1.0.7"
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
.*.swp
|
||||
test/a/
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
language: node_js
|
||||
node_js:
|
||||
- 0.8
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
Copyright (c) Isaac Z. Schlueter ("Author")
|
||||
All rights reserved.
|
||||
|
||||
The BSD License
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
|
||||
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
|
||||
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
|
||||
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
+250
@@ -0,0 +1,250 @@
|
||||
# Glob
|
||||
|
||||
Match files using the patterns the shell uses, like stars and stuff.
|
||||
|
||||
This is a glob implementation in JavaScript. It uses the `minimatch`
|
||||
library to do its matching.
|
||||
|
||||
## Attention: node-glob users!
|
||||
|
||||
The API has changed dramatically between 2.x and 3.x. This library is
|
||||
now 100% JavaScript, and the integer flags have been replaced with an
|
||||
options object.
|
||||
|
||||
Also, there's an event emitter class, proper tests, and all the other
|
||||
things you've come to expect from node modules.
|
||||
|
||||
And best of all, no compilation!
|
||||
|
||||
## Usage
|
||||
|
||||
```javascript
|
||||
var glob = require("glob")
|
||||
|
||||
// options is optional
|
||||
glob("**/*.js", options, function (er, files) {
|
||||
// files is an array of filenames.
|
||||
// If the `nonull` option is set, and nothing
|
||||
// was found, then files is ["**/*.js"]
|
||||
// er is an error object or null.
|
||||
})
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
Please see the [minimatch
|
||||
documentation](https://github.com/isaacs/minimatch) for more details.
|
||||
|
||||
Supports these glob features:
|
||||
|
||||
* Brace Expansion
|
||||
* Extended glob matching
|
||||
* "Globstar" `**` matching
|
||||
|
||||
See:
|
||||
|
||||
* `man sh`
|
||||
* `man bash`
|
||||
* `man 3 fnmatch`
|
||||
* `man 5 gitignore`
|
||||
* [minimatch documentation](https://github.com/isaacs/minimatch)
|
||||
|
||||
## glob(pattern, [options], cb)
|
||||
|
||||
* `pattern` {String} Pattern to be matched
|
||||
* `options` {Object}
|
||||
* `cb` {Function}
|
||||
* `err` {Error | null}
|
||||
* `matches` {Array<String>} filenames found matching the pattern
|
||||
|
||||
Perform an asynchronous glob search.
|
||||
|
||||
## glob.sync(pattern, [options])
|
||||
|
||||
* `pattern` {String} Pattern to be matched
|
||||
* `options` {Object}
|
||||
* return: {Array<String>} filenames found matching the pattern
|
||||
|
||||
Perform a synchronous glob search.
|
||||
|
||||
## Class: glob.Glob
|
||||
|
||||
Create a Glob object by instanting the `glob.Glob` class.
|
||||
|
||||
```javascript
|
||||
var Glob = require("glob").Glob
|
||||
var mg = new Glob(pattern, options, cb)
|
||||
```
|
||||
|
||||
It's an EventEmitter, and starts walking the filesystem to find matches
|
||||
immediately.
|
||||
|
||||
### new glob.Glob(pattern, [options], [cb])
|
||||
|
||||
* `pattern` {String} pattern to search for
|
||||
* `options` {Object}
|
||||
* `cb` {Function} Called when an error occurs, or matches are found
|
||||
* `err` {Error | null}
|
||||
* `matches` {Array<String>} filenames found matching the pattern
|
||||
|
||||
Note that if the `sync` flag is set in the options, then matches will
|
||||
be immediately available on the `g.found` member.
|
||||
|
||||
### Properties
|
||||
|
||||
* `minimatch` The minimatch object that the glob uses.
|
||||
* `options` The options object passed in.
|
||||
* `error` The error encountered. When an error is encountered, the
|
||||
glob object is in an undefined state, and should be discarded.
|
||||
* `aborted` Boolean which is set to true when calling `abort()`. There
|
||||
is no way at this time to continue a glob search after aborting, but
|
||||
you can re-use the statCache to avoid having to duplicate syscalls.
|
||||
* `statCache` Collection of all the stat results the glob search
|
||||
performed.
|
||||
* `cache` Convenience object. Each field has the following possible
|
||||
values:
|
||||
* `false` - Path does not exist
|
||||
* `true` - Path exists
|
||||
* `1` - Path exists, and is not a directory
|
||||
* `2` - Path exists, and is a directory
|
||||
* `[file, entries, ...]` - Path exists, is a directory, and the
|
||||
array value is the results of `fs.readdir`
|
||||
|
||||
### Events
|
||||
|
||||
* `end` When the matching is finished, this is emitted with all the
|
||||
matches found. If the `nonull` option is set, and no match was found,
|
||||
then the `matches` list contains the original pattern. The matches
|
||||
are sorted, unless the `nosort` flag is set.
|
||||
* `match` Every time a match is found, this is emitted with the matched.
|
||||
* `error` Emitted when an unexpected error is encountered, or whenever
|
||||
any fs error occurs if `options.strict` is set.
|
||||
* `abort` When `abort()` is called, this event is raised.
|
||||
|
||||
### Methods
|
||||
|
||||
* `abort` Stop the search.
|
||||
|
||||
### Options
|
||||
|
||||
All the options that can be passed to Minimatch can also be passed to
|
||||
Glob to change pattern matching behavior. Also, some have been added,
|
||||
or have glob-specific ramifications.
|
||||
|
||||
All options are false by default, unless otherwise noted.
|
||||
|
||||
All options are added to the glob object, as well.
|
||||
|
||||
* `cwd` The current working directory in which to search. Defaults
|
||||
to `process.cwd()`.
|
||||
* `root` The place where patterns starting with `/` will be mounted
|
||||
onto. Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix
|
||||
systems, and `C:\` or some such on Windows.)
|
||||
* `dot` Include `.dot` files in normal matches and `globstar` matches.
|
||||
Note that an explicit dot in a portion of the pattern will always
|
||||
match dot files.
|
||||
* `nomount` By default, a pattern starting with a forward-slash will be
|
||||
"mounted" onto the root setting, so that a valid filesystem path is
|
||||
returned. Set this flag to disable that behavior.
|
||||
* `mark` Add a `/` character to directory matches. Note that this
|
||||
requires additional stat calls.
|
||||
* `nosort` Don't sort the results.
|
||||
* `stat` Set to true to stat *all* results. This reduces performance
|
||||
somewhat, and is completely unnecessary, unless `readdir` is presumed
|
||||
to be an untrustworthy indicator of file existence. It will cause
|
||||
ELOOP to be triggered one level sooner in the case of cyclical
|
||||
symbolic links.
|
||||
* `silent` When an unusual error is encountered
|
||||
when attempting to read a directory, a warning will be printed to
|
||||
stderr. Set the `silent` option to true to suppress these warnings.
|
||||
* `strict` When an unusual error is encountered
|
||||
when attempting to read a directory, the process will just continue on
|
||||
in search of other matches. Set the `strict` option to raise an error
|
||||
in these cases.
|
||||
* `cache` See `cache` property above. Pass in a previously generated
|
||||
cache object to save some fs calls.
|
||||
* `statCache` A cache of results of filesystem information, to prevent
|
||||
unnecessary stat calls. While it should not normally be necessary to
|
||||
set this, you may pass the statCache from one glob() call to the
|
||||
options object of another, if you know that the filesystem will not
|
||||
change between calls. (See "Race Conditions" below.)
|
||||
* `sync` Perform a synchronous glob search.
|
||||
* `nounique` In some cases, brace-expanded patterns can result in the
|
||||
same file showing up multiple times in the result set. By default,
|
||||
this implementation prevents duplicates in the result set.
|
||||
Set this flag to disable that behavior.
|
||||
* `nonull` Set to never return an empty set, instead returning a set
|
||||
containing the pattern itself. This is the default in glob(3).
|
||||
* `nocase` Perform a case-insensitive match. Note that case-insensitive
|
||||
filesystems will sometimes result in glob returning results that are
|
||||
case-insensitively matched anyway, since readdir and stat will not
|
||||
raise an error.
|
||||
* `debug` Set to enable debug logging in minimatch and glob.
|
||||
* `globDebug` Set to enable debug logging in glob, but not minimatch.
|
||||
|
||||
## Comparisons to other fnmatch/glob implementations
|
||||
|
||||
While strict compliance with the existing standards is a worthwhile
|
||||
goal, some discrepancies exist between node-glob and other
|
||||
implementations, and are intentional.
|
||||
|
||||
If the pattern starts with a `!` character, then it is negated. Set the
|
||||
`nonegate` flag to suppress this behavior, and treat leading `!`
|
||||
characters normally. This is perhaps relevant if you wish to start the
|
||||
pattern with a negative extglob pattern like `!(a|B)`. Multiple `!`
|
||||
characters at the start of a pattern will negate the pattern multiple
|
||||
times.
|
||||
|
||||
If a pattern starts with `#`, then it is treated as a comment, and
|
||||
will not match anything. Use `\#` to match a literal `#` at the
|
||||
start of a line, or set the `nocomment` flag to suppress this behavior.
|
||||
|
||||
The double-star character `**` is supported by default, unless the
|
||||
`noglobstar` flag is set. This is supported in the manner of bsdglob
|
||||
and bash 4.1, where `**` only has special significance if it is the only
|
||||
thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but
|
||||
`a/**b` will not.
|
||||
|
||||
If an escaped pattern has no matches, and the `nonull` flag is set,
|
||||
then glob returns the pattern as-provided, rather than
|
||||
interpreting the character escapes. For example,
|
||||
`glob.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than
|
||||
`"*a?"`. This is akin to setting the `nullglob` option in bash, except
|
||||
that it does not resolve escaped pattern characters.
|
||||
|
||||
If brace expansion is not disabled, then it is performed before any
|
||||
other interpretation of the glob pattern. Thus, a pattern like
|
||||
`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded
|
||||
**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are
|
||||
checked for validity. Since those two are valid, matching proceeds.
|
||||
|
||||
## Windows
|
||||
|
||||
**Please only use forward-slashes in glob expressions.**
|
||||
|
||||
Though windows uses either `/` or `\` as its path separator, only `/`
|
||||
characters are used by this glob implementation. You must use
|
||||
forward-slashes **only** in glob expressions. Back-slashes will always
|
||||
be interpreted as escape characters, not path separators.
|
||||
|
||||
Results from absolute patterns such as `/foo/*` are mounted onto the
|
||||
root setting using `path.join`. On windows, this will by default result
|
||||
in `/foo/*` matching `C:\foo\bar.txt`.
|
||||
|
||||
## Race Conditions
|
||||
|
||||
Glob searching, by its very nature, is susceptible to race conditions,
|
||||
since it relies on directory walking and such.
|
||||
|
||||
As a result, it is possible that a file that exists when glob looks for
|
||||
it may have been deleted or modified by the time it returns the result.
|
||||
|
||||
As part of its internal implementation, this program caches all stat
|
||||
and readdir calls that it makes, in order to cut down on system
|
||||
overhead. However, this also makes it even more susceptible to races,
|
||||
especially if the cache or statCache objects are reused between glob
|
||||
calls.
|
||||
|
||||
Users are thus advised not to use a glob result as a guarantee of
|
||||
filesystem state in the face of rapid changes. For the vast majority
|
||||
of operations, this is never a problem.
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
var Glob = require("../").Glob
|
||||
|
||||
var pattern = "test/a/**/[cg]/../[cg]"
|
||||
console.log(pattern)
|
||||
|
||||
var mg = new Glob(pattern, {mark: true, sync:true}, function (er, matches) {
|
||||
console.log("matches", matches)
|
||||
})
|
||||
console.log("after")
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
var Glob = require("../").Glob
|
||||
|
||||
var pattern = "{./*/*,/*,/usr/local/*}"
|
||||
console.log(pattern)
|
||||
|
||||
var mg = new Glob(pattern, {mark: true}, function (er, matches) {
|
||||
console.log("matches", matches)
|
||||
})
|
||||
console.log("after")
|
||||
+675
@@ -0,0 +1,675 @@
|
||||
// Approach:
|
||||
//
|
||||
// 1. Get the minimatch set
|
||||
// 2. For each pattern in the set, PROCESS(pattern)
|
||||
// 3. Store matches per-set, then uniq them
|
||||
//
|
||||
// PROCESS(pattern)
|
||||
// Get the first [n] items from pattern that are all strings
|
||||
// Join these together. This is PREFIX.
|
||||
// If there is no more remaining, then stat(PREFIX) and
|
||||
// add to matches if it succeeds. END.
|
||||
// readdir(PREFIX) as ENTRIES
|
||||
// If fails, END
|
||||
// If pattern[n] is GLOBSTAR
|
||||
// // handle the case where the globstar match is empty
|
||||
// // by pruning it out, and testing the resulting pattern
|
||||
// PROCESS(pattern[0..n] + pattern[n+1 .. $])
|
||||
// // handle other cases.
|
||||
// for ENTRY in ENTRIES (not dotfiles)
|
||||
// // attach globstar + tail onto the entry
|
||||
// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $])
|
||||
//
|
||||
// else // not globstar
|
||||
// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
|
||||
// Test ENTRY against pattern[n]
|
||||
// If fails, continue
|
||||
// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
|
||||
//
|
||||
// Caveat:
|
||||
// Cache all stats and readdirs results to minimize syscall. Since all
|
||||
// we ever care about is existence and directory-ness, we can just keep
|
||||
// `true` for files, and [children,...] for directories, or `false` for
|
||||
// things that don't exist.
|
||||
|
||||
|
||||
|
||||
module.exports = glob
|
||||
|
||||
var fs = require("graceful-fs")
|
||||
, minimatch = require("minimatch")
|
||||
, Minimatch = minimatch.Minimatch
|
||||
, inherits = require("inherits")
|
||||
, EE = require("events").EventEmitter
|
||||
, path = require("path")
|
||||
, isDir = {}
|
||||
, assert = require("assert").ok
|
||||
|
||||
function glob (pattern, options, cb) {
|
||||
if (typeof options === "function") cb = options, options = {}
|
||||
if (!options) options = {}
|
||||
|
||||
if (typeof options === "number") {
|
||||
deprecated()
|
||||
return
|
||||
}
|
||||
|
||||
var g = new Glob(pattern, options, cb)
|
||||
return g.sync ? g.found : g
|
||||
}
|
||||
|
||||
glob.fnmatch = deprecated
|
||||
|
||||
function deprecated () {
|
||||
throw new Error("glob's interface has changed. Please see the docs.")
|
||||
}
|
||||
|
||||
glob.sync = globSync
|
||||
function globSync (pattern, options) {
|
||||
if (typeof options === "number") {
|
||||
deprecated()
|
||||
return
|
||||
}
|
||||
|
||||
options = options || {}
|
||||
options.sync = true
|
||||
return glob(pattern, options)
|
||||
}
|
||||
|
||||
|
||||
glob.Glob = Glob
|
||||
inherits(Glob, EE)
|
||||
function Glob (pattern, options, cb) {
|
||||
if (!(this instanceof Glob)) {
|
||||
return new Glob(pattern, options, cb)
|
||||
}
|
||||
|
||||
if (typeof cb === "function") {
|
||||
this.on("error", cb)
|
||||
this.on("end", function (matches) {
|
||||
cb(null, matches)
|
||||
})
|
||||
}
|
||||
|
||||
options = options || {}
|
||||
|
||||
this.EOF = {}
|
||||
this._emitQueue = []
|
||||
|
||||
this.maxDepth = options.maxDepth || 1000
|
||||
this.maxLength = options.maxLength || Infinity
|
||||
this.cache = options.cache || {}
|
||||
this.statCache = options.statCache || {}
|
||||
|
||||
this.changedCwd = false
|
||||
var cwd = process.cwd()
|
||||
if (!options.hasOwnProperty("cwd")) this.cwd = cwd
|
||||
else {
|
||||
this.cwd = options.cwd
|
||||
this.changedCwd = path.resolve(options.cwd) !== cwd
|
||||
}
|
||||
|
||||
this.root = options.root || path.resolve(this.cwd, "/")
|
||||
this.root = path.resolve(this.root)
|
||||
if (process.platform === "win32")
|
||||
this.root = this.root.replace(/\\/g, "/")
|
||||
|
||||
this.nomount = !!options.nomount
|
||||
|
||||
if (!pattern) {
|
||||
throw new Error("must provide pattern")
|
||||
}
|
||||
|
||||
// base-matching: just use globstar for that.
|
||||
if (options.matchBase && -1 === pattern.indexOf("/")) {
|
||||
if (options.noglobstar) {
|
||||
throw new Error("base matching requires globstar")
|
||||
}
|
||||
pattern = "**/" + pattern
|
||||
}
|
||||
|
||||
this.strict = options.strict !== false
|
||||
this.dot = !!options.dot
|
||||
this.mark = !!options.mark
|
||||
this.sync = !!options.sync
|
||||
this.nounique = !!options.nounique
|
||||
this.nonull = !!options.nonull
|
||||
this.nosort = !!options.nosort
|
||||
this.nocase = !!options.nocase
|
||||
this.stat = !!options.stat
|
||||
|
||||
this.debug = !!options.debug || !!options.globDebug
|
||||
if (this.debug)
|
||||
this.log = console.error
|
||||
|
||||
this.silent = !!options.silent
|
||||
|
||||
var mm = this.minimatch = new Minimatch(pattern, options)
|
||||
this.options = mm.options
|
||||
pattern = this.pattern = mm.pattern
|
||||
|
||||
this.error = null
|
||||
this.aborted = false
|
||||
|
||||
// list of all the patterns that ** has resolved do, so
|
||||
// we can avoid visiting multiple times.
|
||||
this._globstars = {}
|
||||
|
||||
EE.call(this)
|
||||
|
||||
// process each pattern in the minimatch set
|
||||
var n = this.minimatch.set.length
|
||||
|
||||
// The matches are stored as {<filename>: true,...} so that
|
||||
// duplicates are automagically pruned.
|
||||
// Later, we do an Object.keys() on these.
|
||||
// Keep them as a list so we can fill in when nonull is set.
|
||||
this.matches = new Array(n)
|
||||
|
||||
this.minimatch.set.forEach(iterator.bind(this))
|
||||
function iterator (pattern, i, set) {
|
||||
this._process(pattern, 0, i, function (er) {
|
||||
if (er) this.emit("error", er)
|
||||
if (-- n <= 0) this._finish()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Glob.prototype.log = function () {}
|
||||
|
||||
Glob.prototype._finish = function () {
|
||||
assert(this instanceof Glob)
|
||||
|
||||
var nou = this.nounique
|
||||
, all = nou ? [] : {}
|
||||
|
||||
for (var i = 0, l = this.matches.length; i < l; i ++) {
|
||||
var matches = this.matches[i]
|
||||
this.log("matches[%d] =", i, matches)
|
||||
// do like the shell, and spit out the literal glob
|
||||
if (!matches) {
|
||||
if (this.nonull) {
|
||||
var literal = this.minimatch.globSet[i]
|
||||
if (nou) all.push(literal)
|
||||
else all[literal] = true
|
||||
}
|
||||
} else {
|
||||
// had matches
|
||||
var m = Object.keys(matches)
|
||||
if (nou) all.push.apply(all, m)
|
||||
else m.forEach(function (m) {
|
||||
all[m] = true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (!nou) all = Object.keys(all)
|
||||
|
||||
if (!this.nosort) {
|
||||
all = all.sort(this.nocase ? alphasorti : alphasort)
|
||||
}
|
||||
|
||||
if (this.mark) {
|
||||
// at *some* point we statted all of these
|
||||
all = all.map(function (m) {
|
||||
var sc = this.cache[m]
|
||||
if (!sc)
|
||||
return m
|
||||
var isDir = (Array.isArray(sc) || sc === 2)
|
||||
if (isDir && m.slice(-1) !== "/") {
|
||||
return m + "/"
|
||||
}
|
||||
if (!isDir && m.slice(-1) === "/") {
|
||||
return m.replace(/\/+$/, "")
|
||||
}
|
||||
return m
|
||||
}, this)
|
||||
}
|
||||
|
||||
this.log("emitting end", all)
|
||||
|
||||
this.EOF = this.found = all
|
||||
this.emitMatch(this.EOF)
|
||||
}
|
||||
|
||||
function alphasorti (a, b) {
|
||||
a = a.toLowerCase()
|
||||
b = b.toLowerCase()
|
||||
return alphasort(a, b)
|
||||
}
|
||||
|
||||
function alphasort (a, b) {
|
||||
return a > b ? 1 : a < b ? -1 : 0
|
||||
}
|
||||
|
||||
Glob.prototype.abort = function () {
|
||||
this.aborted = true
|
||||
this.emit("abort")
|
||||
}
|
||||
|
||||
Glob.prototype.pause = function () {
|
||||
if (this.paused) return
|
||||
if (this.sync)
|
||||
this.emit("error", new Error("Can't pause/resume sync glob"))
|
||||
this.paused = true
|
||||
this.emit("pause")
|
||||
}
|
||||
|
||||
Glob.prototype.resume = function () {
|
||||
if (!this.paused) return
|
||||
if (this.sync)
|
||||
this.emit("error", new Error("Can't pause/resume sync glob"))
|
||||
this.paused = false
|
||||
this.emit("resume")
|
||||
this._processEmitQueue()
|
||||
//process.nextTick(this.emit.bind(this, "resume"))
|
||||
}
|
||||
|
||||
Glob.prototype.emitMatch = function (m) {
|
||||
if (!this.stat || this.statCache[m] || m === this.EOF) {
|
||||
this._emitQueue.push(m)
|
||||
this._processEmitQueue()
|
||||
} else {
|
||||
this._stat(m, function(exists, isDir) {
|
||||
if (exists) {
|
||||
this._emitQueue.push(m)
|
||||
this._processEmitQueue()
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Glob.prototype._processEmitQueue = function (m) {
|
||||
while (!this._processingEmitQueue &&
|
||||
!this.paused) {
|
||||
this._processingEmitQueue = true
|
||||
var m = this._emitQueue.shift()
|
||||
if (!m) {
|
||||
this._processingEmitQueue = false
|
||||
break
|
||||
}
|
||||
|
||||
this.log('emit!', m === this.EOF ? "end" : "match")
|
||||
|
||||
this.emit(m === this.EOF ? "end" : "match", m)
|
||||
this._processingEmitQueue = false
|
||||
}
|
||||
}
|
||||
|
||||
Glob.prototype._process = function (pattern, depth, index, cb_) {
|
||||
assert(this instanceof Glob)
|
||||
|
||||
var cb = function cb (er, res) {
|
||||
assert(this instanceof Glob)
|
||||
if (this.paused) {
|
||||
if (!this._processQueue) {
|
||||
this._processQueue = []
|
||||
this.once("resume", function () {
|
||||
var q = this._processQueue
|
||||
this._processQueue = null
|
||||
q.forEach(function (cb) { cb() })
|
||||
})
|
||||
}
|
||||
this._processQueue.push(cb_.bind(this, er, res))
|
||||
} else {
|
||||
cb_.call(this, er, res)
|
||||
}
|
||||
}.bind(this)
|
||||
|
||||
if (this.aborted) return cb()
|
||||
|
||||
if (depth > this.maxDepth) return cb()
|
||||
|
||||
// Get the first [n] parts of pattern that are all strings.
|
||||
var n = 0
|
||||
while (typeof pattern[n] === "string") {
|
||||
n ++
|
||||
}
|
||||
// now n is the index of the first one that is *not* a string.
|
||||
|
||||
// see if there's anything else
|
||||
var prefix
|
||||
switch (n) {
|
||||
// if not, then this is rather simple
|
||||
case pattern.length:
|
||||
prefix = pattern.join("/")
|
||||
this._stat(prefix, function (exists, isDir) {
|
||||
// either it's there, or it isn't.
|
||||
// nothing more to do, either way.
|
||||
if (exists) {
|
||||
if (prefix && isAbsolute(prefix) && !this.nomount) {
|
||||
if (prefix.charAt(0) === "/") {
|
||||
prefix = path.join(this.root, prefix)
|
||||
} else {
|
||||
prefix = path.resolve(this.root, prefix)
|
||||
}
|
||||
}
|
||||
|
||||
if (process.platform === "win32")
|
||||
prefix = prefix.replace(/\\/g, "/")
|
||||
|
||||
this.matches[index] = this.matches[index] || {}
|
||||
this.matches[index][prefix] = true
|
||||
this.emitMatch(prefix)
|
||||
}
|
||||
return cb()
|
||||
})
|
||||
return
|
||||
|
||||
case 0:
|
||||
// pattern *starts* with some non-trivial item.
|
||||
// going to readdir(cwd), but not include the prefix in matches.
|
||||
prefix = null
|
||||
break
|
||||
|
||||
default:
|
||||
// pattern has some string bits in the front.
|
||||
// whatever it starts with, whether that's "absolute" like /foo/bar,
|
||||
// or "relative" like "../baz"
|
||||
prefix = pattern.slice(0, n)
|
||||
prefix = prefix.join("/")
|
||||
break
|
||||
}
|
||||
|
||||
// get the list of entries.
|
||||
var read
|
||||
if (prefix === null) read = "."
|
||||
else if (isAbsolute(prefix) || isAbsolute(pattern.join("/"))) {
|
||||
if (!prefix || !isAbsolute(prefix)) {
|
||||
prefix = path.join("/", prefix)
|
||||
}
|
||||
read = prefix = path.resolve(prefix)
|
||||
|
||||
// if (process.platform === "win32")
|
||||
// read = prefix = prefix.replace(/^[a-zA-Z]:|\\/g, "/")
|
||||
|
||||
this.log('absolute: ', prefix, this.root, pattern, read)
|
||||
} else {
|
||||
read = prefix
|
||||
}
|
||||
|
||||
this.log('readdir(%j)', read, this.cwd, this.root)
|
||||
|
||||
return this._readdir(read, function (er, entries) {
|
||||
if (er) {
|
||||
// not a directory!
|
||||
// this means that, whatever else comes after this, it can never match
|
||||
return cb()
|
||||
}
|
||||
|
||||
// globstar is special
|
||||
if (pattern[n] === minimatch.GLOBSTAR) {
|
||||
// test without the globstar, and with every child both below
|
||||
// and replacing the globstar.
|
||||
var s = [ pattern.slice(0, n).concat(pattern.slice(n + 1)) ]
|
||||
entries.forEach(function (e) {
|
||||
if (e.charAt(0) === "." && !this.dot) return
|
||||
// instead of the globstar
|
||||
s.push(pattern.slice(0, n).concat(e).concat(pattern.slice(n + 1)))
|
||||
// below the globstar
|
||||
s.push(pattern.slice(0, n).concat(e).concat(pattern.slice(n)))
|
||||
}, this)
|
||||
|
||||
s = s.filter(function (pattern) {
|
||||
var key = gsKey(pattern)
|
||||
var seen = !this._globstars[key]
|
||||
this._globstars[key] = true
|
||||
return seen
|
||||
}, this)
|
||||
|
||||
if (!s.length)
|
||||
return cb()
|
||||
|
||||
// now asyncForEach over this
|
||||
var l = s.length
|
||||
, errState = null
|
||||
s.forEach(function (gsPattern) {
|
||||
this._process(gsPattern, depth + 1, index, function (er) {
|
||||
if (errState) return
|
||||
if (er) return cb(errState = er)
|
||||
if (--l <= 0) return cb()
|
||||
})
|
||||
}, this)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// not a globstar
|
||||
// It will only match dot entries if it starts with a dot, or if
|
||||
// dot is set. Stuff like @(.foo|.bar) isn't allowed.
|
||||
var pn = pattern[n]
|
||||
var rawGlob = pattern[n]._glob
|
||||
, dotOk = this.dot || rawGlob.charAt(0) === "."
|
||||
|
||||
entries = entries.filter(function (e) {
|
||||
return (e.charAt(0) !== "." || dotOk) &&
|
||||
e.match(pattern[n])
|
||||
})
|
||||
|
||||
// If n === pattern.length - 1, then there's no need for the extra stat
|
||||
// *unless* the user has specified "mark" or "stat" explicitly.
|
||||
// We know that they exist, since the readdir returned them.
|
||||
if (n === pattern.length - 1 &&
|
||||
!this.mark &&
|
||||
!this.stat) {
|
||||
entries.forEach(function (e) {
|
||||
if (prefix) {
|
||||
if (prefix !== "/") e = prefix + "/" + e
|
||||
else e = prefix + e
|
||||
}
|
||||
if (e.charAt(0) === "/" && !this.nomount) {
|
||||
e = path.join(this.root, e)
|
||||
}
|
||||
|
||||
if (process.platform === "win32")
|
||||
e = e.replace(/\\/g, "/")
|
||||
|
||||
this.matches[index] = this.matches[index] || {}
|
||||
this.matches[index][e] = true
|
||||
this.emitMatch(e)
|
||||
}, this)
|
||||
return cb.call(this)
|
||||
}
|
||||
|
||||
|
||||
// now test all the remaining entries as stand-ins for that part
|
||||
// of the pattern.
|
||||
var l = entries.length
|
||||
, errState = null
|
||||
if (l === 0) return cb() // no matches possible
|
||||
entries.forEach(function (e) {
|
||||
var p = pattern.slice(0, n).concat(e).concat(pattern.slice(n + 1))
|
||||
this._process(p, depth + 1, index, function (er) {
|
||||
if (errState) return
|
||||
if (er) return cb(errState = er)
|
||||
if (--l === 0) return cb.call(this)
|
||||
})
|
||||
}, this)
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
function gsKey (pattern) {
|
||||
return '**' + pattern.map(function (p) {
|
||||
return (p === minimatch.GLOBSTAR) ? '**' : (''+p)
|
||||
}).join('/')
|
||||
}
|
||||
|
||||
Glob.prototype._stat = function (f, cb) {
|
||||
assert(this instanceof Glob)
|
||||
var abs = f
|
||||
if (f.charAt(0) === "/") {
|
||||
abs = path.join(this.root, f)
|
||||
} else if (this.changedCwd) {
|
||||
abs = path.resolve(this.cwd, f)
|
||||
}
|
||||
|
||||
if (f.length > this.maxLength) {
|
||||
var er = new Error("Path name too long")
|
||||
er.code = "ENAMETOOLONG"
|
||||
er.path = f
|
||||
return this._afterStat(f, abs, cb, er)
|
||||
}
|
||||
|
||||
this.log('stat', [this.cwd, f, '=', abs])
|
||||
|
||||
if (!this.stat && this.cache.hasOwnProperty(f)) {
|
||||
var exists = this.cache[f]
|
||||
, isDir = exists && (Array.isArray(exists) || exists === 2)
|
||||
if (this.sync) return cb.call(this, !!exists, isDir)
|
||||
return process.nextTick(cb.bind(this, !!exists, isDir))
|
||||
}
|
||||
|
||||
var stat = this.statCache[abs]
|
||||
if (this.sync || stat) {
|
||||
var er
|
||||
try {
|
||||
stat = fs.statSync(abs)
|
||||
} catch (e) {
|
||||
er = e
|
||||
}
|
||||
this._afterStat(f, abs, cb, er, stat)
|
||||
} else {
|
||||
fs.stat(abs, this._afterStat.bind(this, f, abs, cb))
|
||||
}
|
||||
}
|
||||
|
||||
Glob.prototype._afterStat = function (f, abs, cb, er, stat) {
|
||||
var exists
|
||||
assert(this instanceof Glob)
|
||||
|
||||
if (abs.slice(-1) === "/" && stat && !stat.isDirectory()) {
|
||||
this.log("should be ENOTDIR, fake it")
|
||||
|
||||
er = new Error("ENOTDIR, not a directory '" + abs + "'")
|
||||
er.path = abs
|
||||
er.code = "ENOTDIR"
|
||||
stat = null
|
||||
}
|
||||
|
||||
var emit = !this.statCache[abs]
|
||||
this.statCache[abs] = stat
|
||||
|
||||
if (er || !stat) {
|
||||
exists = false
|
||||
} else {
|
||||
exists = stat.isDirectory() ? 2 : 1
|
||||
if (emit)
|
||||
this.emit('stat', f, stat)
|
||||
}
|
||||
this.cache[f] = this.cache[f] || exists
|
||||
cb.call(this, !!exists, exists === 2)
|
||||
}
|
||||
|
||||
Glob.prototype._readdir = function (f, cb) {
|
||||
assert(this instanceof Glob)
|
||||
var abs = f
|
||||
if (f.charAt(0) === "/") {
|
||||
abs = path.join(this.root, f)
|
||||
} else if (isAbsolute(f)) {
|
||||
abs = f
|
||||
} else if (this.changedCwd) {
|
||||
abs = path.resolve(this.cwd, f)
|
||||
}
|
||||
|
||||
if (f.length > this.maxLength) {
|
||||
var er = new Error("Path name too long")
|
||||
er.code = "ENAMETOOLONG"
|
||||
er.path = f
|
||||
return this._afterReaddir(f, abs, cb, er)
|
||||
}
|
||||
|
||||
this.log('readdir', [this.cwd, f, abs])
|
||||
if (this.cache.hasOwnProperty(f)) {
|
||||
var c = this.cache[f]
|
||||
if (Array.isArray(c)) {
|
||||
if (this.sync) return cb.call(this, null, c)
|
||||
return process.nextTick(cb.bind(this, null, c))
|
||||
}
|
||||
|
||||
if (!c || c === 1) {
|
||||
// either ENOENT or ENOTDIR
|
||||
var code = c ? "ENOTDIR" : "ENOENT"
|
||||
, er = new Error((c ? "Not a directory" : "Not found") + ": " + f)
|
||||
er.path = f
|
||||
er.code = code
|
||||
this.log(f, er)
|
||||
if (this.sync) return cb.call(this, er)
|
||||
return process.nextTick(cb.bind(this, er))
|
||||
}
|
||||
|
||||
// at this point, c === 2, meaning it's a dir, but we haven't
|
||||
// had to read it yet, or c === true, meaning it's *something*
|
||||
// but we don't have any idea what. Need to read it, either way.
|
||||
}
|
||||
|
||||
if (this.sync) {
|
||||
var er, entries
|
||||
try {
|
||||
entries = fs.readdirSync(abs)
|
||||
} catch (e) {
|
||||
er = e
|
||||
}
|
||||
return this._afterReaddir(f, abs, cb, er, entries)
|
||||
}
|
||||
|
||||
fs.readdir(abs, this._afterReaddir.bind(this, f, abs, cb))
|
||||
}
|
||||
|
||||
Glob.prototype._afterReaddir = function (f, abs, cb, er, entries) {
|
||||
assert(this instanceof Glob)
|
||||
if (entries && !er) {
|
||||
this.cache[f] = entries
|
||||
// if we haven't asked to stat everything for suresies, then just
|
||||
// assume that everything in there exists, so we can avoid
|
||||
// having to stat it a second time. This also gets us one step
|
||||
// further into ELOOP territory.
|
||||
if (!this.mark && !this.stat) {
|
||||
entries.forEach(function (e) {
|
||||
if (f === "/") e = f + e
|
||||
else e = f + "/" + e
|
||||
this.cache[e] = true
|
||||
}, this)
|
||||
}
|
||||
|
||||
return cb.call(this, er, entries)
|
||||
}
|
||||
|
||||
// now handle errors, and cache the information
|
||||
if (er) switch (er.code) {
|
||||
case "ENOTDIR": // totally normal. means it *does* exist.
|
||||
this.cache[f] = 1
|
||||
return cb.call(this, er)
|
||||
case "ENOENT": // not terribly unusual
|
||||
case "ELOOP":
|
||||
case "ENAMETOOLONG":
|
||||
case "UNKNOWN":
|
||||
this.cache[f] = false
|
||||
return cb.call(this, er)
|
||||
default: // some unusual error. Treat as failure.
|
||||
this.cache[f] = false
|
||||
if (this.strict) this.emit("error", er)
|
||||
if (!this.silent) console.error("glob error", er)
|
||||
return cb.call(this, er)
|
||||
}
|
||||
}
|
||||
|
||||
var isAbsolute = process.platform === "win32" ? absWin : absUnix
|
||||
|
||||
function absWin (p) {
|
||||
if (absUnix(p)) return true
|
||||
// pull off the device/UNC bit from a windows path.
|
||||
// from node's lib/path.js
|
||||
var splitDeviceRe =
|
||||
/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/
|
||||
, result = splitDeviceRe.exec(p)
|
||||
, device = result[1] || ''
|
||||
, isUnc = device && device.charAt(1) !== ':'
|
||||
, isAbsolute = !!result[2] || isUnc // UNC paths are always absolute
|
||||
|
||||
return isAbsolute
|
||||
}
|
||||
|
||||
function absUnix (p) {
|
||||
return p.charAt(0) === "/" || p === ""
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
node_modules/
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
Copyright (c) Isaac Z. Schlueter ("Author")
|
||||
All rights reserved.
|
||||
|
||||
The BSD License
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
|
||||
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
|
||||
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
|
||||
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
# graceful-fs
|
||||
|
||||
graceful-fs functions as a drop-in replacement for the fs module,
|
||||
making various improvements.
|
||||
|
||||
The improvements are meant to normalize behavior across different
|
||||
platforms and environments, and to make filesystem access more
|
||||
resilient to errors.
|
||||
|
||||
## Improvements over fs module
|
||||
|
||||
graceful-fs:
|
||||
|
||||
* Queues up `open` and `readdir` calls, and retries them once
|
||||
something closes if there is an EMFILE error from too many file
|
||||
descriptors.
|
||||
* fixes `lchmod` for Node versions prior to 0.6.2.
|
||||
* implements `fs.lutimes` if possible. Otherwise it becomes a noop.
|
||||
* ignores `EINVAL` and `EPERM` errors in `chown`, `fchown` or
|
||||
`lchown` if the user isn't root.
|
||||
* makes `lchmod` and `lchown` become noops, if not available.
|
||||
* retries reading a file if `read` results in EAGAIN error.
|
||||
|
||||
On Windows, it retries renaming a file for up to one second if `EACCESS`
|
||||
or `EPERM` error occurs, likely because antivirus software has locked
|
||||
the directory.
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
// Monkey-patching the fs module.
|
||||
// It's ugly, but there is simply no other way to do this.
|
||||
var fs = module.exports = require('fs')
|
||||
|
||||
var assert = require('assert')
|
||||
|
||||
// fix up some busted stuff, mostly on windows and old nodes
|
||||
require('./polyfills.js')
|
||||
|
||||
// The EMFILE enqueuing stuff
|
||||
|
||||
var util = require('util')
|
||||
|
||||
function noop () {}
|
||||
|
||||
var debug = noop
|
||||
var util = require('util')
|
||||
if (util.debuglog)
|
||||
debug = util.debuglog('gfs')
|
||||
else if (/\bgfs\b/i.test(process.env.NODE_DEBUG || ''))
|
||||
debug = function() {
|
||||
var m = util.format.apply(util, arguments)
|
||||
m = 'GFS: ' + m.split(/\n/).join('\nGFS: ')
|
||||
console.error(m)
|
||||
}
|
||||
|
||||
if (/\bgfs\b/i.test(process.env.NODE_DEBUG || '')) {
|
||||
process.on('exit', function() {
|
||||
debug('fds', fds)
|
||||
debug(queue)
|
||||
assert.equal(queue.length, 0)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
var originalOpen = fs.open
|
||||
fs.open = open
|
||||
|
||||
function open(path, flags, mode, cb) {
|
||||
if (typeof mode === "function") cb = mode, mode = null
|
||||
if (typeof cb !== "function") cb = noop
|
||||
new OpenReq(path, flags, mode, cb)
|
||||
}
|
||||
|
||||
function OpenReq(path, flags, mode, cb) {
|
||||
this.path = path
|
||||
this.flags = flags
|
||||
this.mode = mode
|
||||
this.cb = cb
|
||||
Req.call(this)
|
||||
}
|
||||
|
||||
util.inherits(OpenReq, Req)
|
||||
|
||||
OpenReq.prototype.process = function() {
|
||||
originalOpen.call(fs, this.path, this.flags, this.mode, this.done)
|
||||
}
|
||||
|
||||
var fds = {}
|
||||
OpenReq.prototype.done = function(er, fd) {
|
||||
debug('open done', er, fd)
|
||||
if (fd)
|
||||
fds['fd' + fd] = this.path
|
||||
Req.prototype.done.call(this, er, fd)
|
||||
}
|
||||
|
||||
|
||||
var originalReaddir = fs.readdir
|
||||
fs.readdir = readdir
|
||||
|
||||
function readdir(path, cb) {
|
||||
if (typeof cb !== "function") cb = noop
|
||||
new ReaddirReq(path, cb)
|
||||
}
|
||||
|
||||
function ReaddirReq(path, cb) {
|
||||
this.path = path
|
||||
this.cb = cb
|
||||
Req.call(this)
|
||||
}
|
||||
|
||||
util.inherits(ReaddirReq, Req)
|
||||
|
||||
ReaddirReq.prototype.process = function() {
|
||||
originalReaddir.call(fs, this.path, this.done)
|
||||
}
|
||||
|
||||
ReaddirReq.prototype.done = function(er, files) {
|
||||
Req.prototype.done.call(this, er, files)
|
||||
onclose()
|
||||
}
|
||||
|
||||
|
||||
var originalClose = fs.close
|
||||
fs.close = close
|
||||
|
||||
function close (fd, cb) {
|
||||
debug('close', fd)
|
||||
if (typeof cb !== "function") cb = noop
|
||||
delete fds['fd' + fd]
|
||||
originalClose.call(fs, fd, function(er) {
|
||||
onclose()
|
||||
cb(er)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
var originalCloseSync = fs.closeSync
|
||||
fs.closeSync = closeSync
|
||||
|
||||
function closeSync (fd) {
|
||||
try {
|
||||
return originalCloseSync(fd)
|
||||
} finally {
|
||||
onclose()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Req class
|
||||
function Req () {
|
||||
// start processing
|
||||
this.done = this.done.bind(this)
|
||||
this.failures = 0
|
||||
this.process()
|
||||
}
|
||||
|
||||
Req.prototype.done = function (er, result) {
|
||||
var tryAgain = false
|
||||
if (er) {
|
||||
var code = er.code
|
||||
var tryAgain = code === "EMFILE"
|
||||
if (process.platform === "win32")
|
||||
tryAgain = tryAgain || code === "OK"
|
||||
}
|
||||
|
||||
if (tryAgain) {
|
||||
this.failures ++
|
||||
enqueue(this)
|
||||
} else {
|
||||
var cb = this.cb
|
||||
cb(er, result)
|
||||
}
|
||||
}
|
||||
|
||||
var queue = []
|
||||
|
||||
function enqueue(req) {
|
||||
queue.push(req)
|
||||
debug('enqueue %d %s', queue.length, req.constructor.name, req)
|
||||
}
|
||||
|
||||
function onclose() {
|
||||
var req = queue.shift()
|
||||
if (req) {
|
||||
debug('process', req.constructor.name, req)
|
||||
req.process()
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"author": {
|
||||
"name": "Isaac Z. Schlueter",
|
||||
"email": "i@izs.me",
|
||||
"url": "http://blog.izs.me"
|
||||
},
|
||||
"name": "graceful-fs",
|
||||
"description": "A drop-in replacement for fs, making various improvements.",
|
||||
"version": "2.0.1",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/isaacs/node-graceful-fs.git"
|
||||
},
|
||||
"main": "graceful-fs.js",
|
||||
"engines": {
|
||||
"node": ">=0.4.0"
|
||||
},
|
||||
"directories": {
|
||||
"test": "test"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "tap test/*.js"
|
||||
},
|
||||
"keywords": [
|
||||
"fs",
|
||||
"module",
|
||||
"reading",
|
||||
"retry",
|
||||
"retries",
|
||||
"queue",
|
||||
"error",
|
||||
"errors",
|
||||
"handling",
|
||||
"EMFILE",
|
||||
"EAGAIN",
|
||||
"EINVAL",
|
||||
"EPERM",
|
||||
"EACCESS"
|
||||
],
|
||||
"license": "BSD",
|
||||
"readme": "# graceful-fs\n\ngraceful-fs functions as a drop-in replacement for the fs module,\nmaking various improvements.\n\nThe improvements are meant to normalize behavior across different\nplatforms and environments, and to make filesystem access more\nresilient to errors.\n\n## Improvements over fs module\n\ngraceful-fs:\n\n* Queues up `open` and `readdir` calls, and retries them once\n something closes if there is an EMFILE error from too many file\n descriptors.\n* fixes `lchmod` for Node versions prior to 0.6.2.\n* implements `fs.lutimes` if possible. Otherwise it becomes a noop.\n* ignores `EINVAL` and `EPERM` errors in `chown`, `fchown` or\n `lchown` if the user isn't root.\n* makes `lchmod` and `lchown` become noops, if not available.\n* retries reading a file if `read` results in EAGAIN error.\n\nOn Windows, it retries renaming a file for up to one second if `EACCESS`\nor `EPERM` error occurs, likely because antivirus software has locked\nthe directory.\n",
|
||||
"readmeFilename": "README.md",
|
||||
"bugs": {
|
||||
"url": "https://github.com/isaacs/node-graceful-fs/issues"
|
||||
},
|
||||
"homepage": "https://github.com/isaacs/node-graceful-fs",
|
||||
"_id": "graceful-fs@2.0.1",
|
||||
"_from": "graceful-fs@~2.0.0"
|
||||
}
|
||||
+228
@@ -0,0 +1,228 @@
|
||||
var fs = require('fs')
|
||||
var constants = require('constants')
|
||||
|
||||
var origCwd = process.cwd
|
||||
var cwd = null
|
||||
process.cwd = function() {
|
||||
if (!cwd)
|
||||
cwd = origCwd.call(process)
|
||||
return cwd
|
||||
}
|
||||
var chdir = process.chdir
|
||||
process.chdir = function(d) {
|
||||
cwd = null
|
||||
chdir.call(process, d)
|
||||
}
|
||||
|
||||
// (re-)implement some things that are known busted or missing.
|
||||
|
||||
// lchmod, broken prior to 0.6.2
|
||||
// back-port the fix here.
|
||||
if (constants.hasOwnProperty('O_SYMLINK') &&
|
||||
process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
|
||||
fs.lchmod = function (path, mode, callback) {
|
||||
callback = callback || noop
|
||||
fs.open( path
|
||||
, constants.O_WRONLY | constants.O_SYMLINK
|
||||
, mode
|
||||
, function (err, fd) {
|
||||
if (err) {
|
||||
callback(err)
|
||||
return
|
||||
}
|
||||
// prefer to return the chmod error, if one occurs,
|
||||
// but still try to close, and report closing errors if they occur.
|
||||
fs.fchmod(fd, mode, function (err) {
|
||||
fs.close(fd, function(err2) {
|
||||
callback(err || err2)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fs.lchmodSync = function (path, mode) {
|
||||
var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode)
|
||||
|
||||
// prefer to return the chmod error, if one occurs,
|
||||
// but still try to close, and report closing errors if they occur.
|
||||
var err, err2
|
||||
try {
|
||||
var ret = fs.fchmodSync(fd, mode)
|
||||
} catch (er) {
|
||||
err = er
|
||||
}
|
||||
try {
|
||||
fs.closeSync(fd)
|
||||
} catch (er) {
|
||||
err2 = er
|
||||
}
|
||||
if (err || err2) throw (err || err2)
|
||||
return ret
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// lutimes implementation, or no-op
|
||||
if (!fs.lutimes) {
|
||||
if (constants.hasOwnProperty("O_SYMLINK")) {
|
||||
fs.lutimes = function (path, at, mt, cb) {
|
||||
fs.open(path, constants.O_SYMLINK, function (er, fd) {
|
||||
cb = cb || noop
|
||||
if (er) return cb(er)
|
||||
fs.futimes(fd, at, mt, function (er) {
|
||||
fs.close(fd, function (er2) {
|
||||
return cb(er || er2)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fs.lutimesSync = function (path, at, mt) {
|
||||
var fd = fs.openSync(path, constants.O_SYMLINK)
|
||||
, err
|
||||
, err2
|
||||
, ret
|
||||
|
||||
try {
|
||||
var ret = fs.futimesSync(fd, at, mt)
|
||||
} catch (er) {
|
||||
err = er
|
||||
}
|
||||
try {
|
||||
fs.closeSync(fd)
|
||||
} catch (er) {
|
||||
err2 = er
|
||||
}
|
||||
if (err || err2) throw (err || err2)
|
||||
return ret
|
||||
}
|
||||
|
||||
} else if (fs.utimensat && constants.hasOwnProperty("AT_SYMLINK_NOFOLLOW")) {
|
||||
// maybe utimensat will be bound soonish?
|
||||
fs.lutimes = function (path, at, mt, cb) {
|
||||
fs.utimensat(path, at, mt, constants.AT_SYMLINK_NOFOLLOW, cb)
|
||||
}
|
||||
|
||||
fs.lutimesSync = function (path, at, mt) {
|
||||
return fs.utimensatSync(path, at, mt, constants.AT_SYMLINK_NOFOLLOW)
|
||||
}
|
||||
|
||||
} else {
|
||||
fs.lutimes = function (_a, _b, _c, cb) { process.nextTick(cb) }
|
||||
fs.lutimesSync = function () {}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// https://github.com/isaacs/node-graceful-fs/issues/4
|
||||
// Chown should not fail on einval or eperm if non-root.
|
||||
|
||||
fs.chown = chownFix(fs.chown)
|
||||
fs.fchown = chownFix(fs.fchown)
|
||||
fs.lchown = chownFix(fs.lchown)
|
||||
|
||||
fs.chownSync = chownFixSync(fs.chownSync)
|
||||
fs.fchownSync = chownFixSync(fs.fchownSync)
|
||||
fs.lchownSync = chownFixSync(fs.lchownSync)
|
||||
|
||||
function chownFix (orig) {
|
||||
if (!orig) return orig
|
||||
return function (target, uid, gid, cb) {
|
||||
return orig.call(fs, target, uid, gid, function (er, res) {
|
||||
if (chownErOk(er)) er = null
|
||||
cb(er, res)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function chownFixSync (orig) {
|
||||
if (!orig) return orig
|
||||
return function (target, uid, gid) {
|
||||
try {
|
||||
return orig.call(fs, target, uid, gid)
|
||||
} catch (er) {
|
||||
if (!chownErOk(er)) throw er
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function chownErOk (er) {
|
||||
// if there's no getuid, or if getuid() is something other than 0,
|
||||
// and the error is EINVAL or EPERM, then just ignore it.
|
||||
// This specific case is a silent failure in cp, install, tar,
|
||||
// and most other unix tools that manage permissions.
|
||||
// When running as root, or if other types of errors are encountered,
|
||||
// then it's strict.
|
||||
if (!er || (!process.getuid || process.getuid() !== 0)
|
||||
&& (er.code === "EINVAL" || er.code === "EPERM")) return true
|
||||
}
|
||||
|
||||
|
||||
// if lchmod/lchown do not exist, then make them no-ops
|
||||
if (!fs.lchmod) {
|
||||
fs.lchmod = function (path, mode, cb) {
|
||||
process.nextTick(cb)
|
||||
}
|
||||
fs.lchmodSync = function () {}
|
||||
}
|
||||
if (!fs.lchown) {
|
||||
fs.lchown = function (path, uid, gid, cb) {
|
||||
process.nextTick(cb)
|
||||
}
|
||||
fs.lchownSync = function () {}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// on Windows, A/V software can lock the directory, causing this
|
||||
// to fail with an EACCES or EPERM if the directory contains newly
|
||||
// created files. Try again on failure, for up to 1 second.
|
||||
if (process.platform === "win32") {
|
||||
var rename_ = fs.rename
|
||||
fs.rename = function rename (from, to, cb) {
|
||||
var start = Date.now()
|
||||
rename_(from, to, function CB (er) {
|
||||
if (er
|
||||
&& (er.code === "EACCES" || er.code === "EPERM")
|
||||
&& Date.now() - start < 1000) {
|
||||
return rename_(from, to, CB)
|
||||
}
|
||||
cb(er)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// if read() returns EAGAIN, then just try it again.
|
||||
var read = fs.read
|
||||
fs.read = function (fd, buffer, offset, length, position, callback_) {
|
||||
var callback
|
||||
if (callback_ && typeof callback_ === 'function') {
|
||||
var eagCounter = 0
|
||||
callback = function (er, _, __) {
|
||||
if (er && er.code === 'EAGAIN' && eagCounter < 10) {
|
||||
eagCounter ++
|
||||
return read.call(fs, fd, buffer, offset, length, position, callback)
|
||||
}
|
||||
callback_.apply(this, arguments)
|
||||
}
|
||||
}
|
||||
return read.call(fs, fd, buffer, offset, length, position, callback)
|
||||
}
|
||||
|
||||
var readSync = fs.readSync
|
||||
fs.readSync = function (fd, buffer, offset, length, position) {
|
||||
var eagCounter = 0
|
||||
while (true) {
|
||||
try {
|
||||
return readSync.call(fs, fd, buffer, offset, length, position)
|
||||
} catch (er) {
|
||||
if (er.code === 'EAGAIN' && eagCounter < 10) {
|
||||
eagCounter ++
|
||||
continue
|
||||
}
|
||||
throw er
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
var test = require('tap').test
|
||||
var fs = require('../graceful-fs.js')
|
||||
|
||||
test('graceful fs is monkeypatched fs', function (t) {
|
||||
t.equal(fs, require('fs'))
|
||||
t.end()
|
||||
})
|
||||
|
||||
test('open an existing file works', function (t) {
|
||||
var fd = fs.openSync(__filename, 'r')
|
||||
fs.closeSync(fd)
|
||||
fs.open(__filename, 'r', function (er, fd) {
|
||||
if (er) throw er
|
||||
fs.close(fd, function (er) {
|
||||
if (er) throw er
|
||||
t.pass('works')
|
||||
t.end()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
test('open a non-existing file throws', function (t) {
|
||||
var er
|
||||
try {
|
||||
var fd = fs.openSync('this file does not exist', 'r')
|
||||
} catch (x) {
|
||||
er = x
|
||||
}
|
||||
t.ok(er, 'should throw')
|
||||
t.notOk(fd, 'should not get an fd')
|
||||
t.equal(er.code, 'ENOENT')
|
||||
|
||||
fs.open('neither does this file', 'r', function (er, fd) {
|
||||
t.ok(er, 'should throw')
|
||||
t.notOk(fd, 'should not get an fd')
|
||||
t.equal(er.code, 'ENOENT')
|
||||
t.end()
|
||||
})
|
||||
})
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
The ISC License
|
||||
|
||||
Copyright (c) Isaac Z. Schlueter
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted, provided that the above
|
||||
copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
Browser-friendly inheritance fully compatible with standard node.js
|
||||
[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor).
|
||||
|
||||
This package exports standard `inherits` from node.js `util` module in
|
||||
node environment, but also provides alternative browser-friendly
|
||||
implementation through [browser
|
||||
field](https://gist.github.com/shtylman/4339901). Alternative
|
||||
implementation is a literal copy of standard one located in standalone
|
||||
module to avoid requiring of `util`. It also has a shim for old
|
||||
browsers with no `Object.create` support.
|
||||
|
||||
While keeping you sure you are using standard `inherits`
|
||||
implementation in node.js environment, it allows bundlers such as
|
||||
[browserify](https://github.com/substack/node-browserify) to not
|
||||
include full `util` package to your client code if all you need is
|
||||
just `inherits` function. It worth, because browser shim for `util`
|
||||
package is large and `inherits` is often the single function you need
|
||||
from it.
|
||||
|
||||
It's recommended to use this package instead of
|
||||
`require('util').inherits` for any code that has chances to be used
|
||||
not only in node.js but in browser too.
|
||||
|
||||
## usage
|
||||
|
||||
```js
|
||||
var inherits = require('inherits');
|
||||
// then use exactly as the standard one
|
||||
```
|
||||
|
||||
## note on version ~1.0
|
||||
|
||||
Version ~1.0 had completely different motivation and is not compatible
|
||||
neither with 2.0 nor with standard node.js `inherits`.
|
||||
|
||||
If you are using version ~1.0 and planning to switch to ~2.0, be
|
||||
careful:
|
||||
|
||||
* new version uses `super_` instead of `super` for referencing
|
||||
superclass
|
||||
* new version overwrites current prototype while old one preserves any
|
||||
existing fields on it
|
||||
+1
@@ -0,0 +1 @@
|
||||
module.exports = require('util').inherits
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
if (typeof Object.create === 'function') {
|
||||
// implementation from standard node.js 'util' module
|
||||
module.exports = function inherits(ctor, superCtor) {
|
||||
ctor.super_ = superCtor
|
||||
ctor.prototype = Object.create(superCtor.prototype, {
|
||||
constructor: {
|
||||
value: ctor,
|
||||
enumerable: false,
|
||||
writable: true,
|
||||
configurable: true
|
||||
}
|
||||
});
|
||||
};
|
||||
} else {
|
||||
// old school shim for old browsers
|
||||
module.exports = function inherits(ctor, superCtor) {
|
||||
ctor.super_ = superCtor
|
||||
var TempCtor = function () {}
|
||||
TempCtor.prototype = superCtor.prototype
|
||||
ctor.prototype = new TempCtor()
|
||||
ctor.prototype.constructor = ctor
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"name": "inherits",
|
||||
"description": "Browser-friendly inheritance fully compatible with standard node.js inherits()",
|
||||
"version": "2.0.1",
|
||||
"keywords": [
|
||||
"inheritance",
|
||||
"class",
|
||||
"klass",
|
||||
"oop",
|
||||
"object-oriented",
|
||||
"inherits",
|
||||
"browser",
|
||||
"browserify"
|
||||
],
|
||||
"main": "./inherits.js",
|
||||
"browser": "./inherits_browser.js",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/isaacs/inherits"
|
||||
},
|
||||
"license": "ISC",
|
||||
"scripts": {
|
||||
"test": "node test"
|
||||
},
|
||||
"readme": "Browser-friendly inheritance fully compatible with standard node.js\n[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor).\n\nThis package exports standard `inherits` from node.js `util` module in\nnode environment, but also provides alternative browser-friendly\nimplementation through [browser\nfield](https://gist.github.com/shtylman/4339901). Alternative\nimplementation is a literal copy of standard one located in standalone\nmodule to avoid requiring of `util`. It also has a shim for old\nbrowsers with no `Object.create` support.\n\nWhile keeping you sure you are using standard `inherits`\nimplementation in node.js environment, it allows bundlers such as\n[browserify](https://github.com/substack/node-browserify) to not\ninclude full `util` package to your client code if all you need is\njust `inherits` function. It worth, because browser shim for `util`\npackage is large and `inherits` is often the single function you need\nfrom it.\n\nIt's recommended to use this package instead of\n`require('util').inherits` for any code that has chances to be used\nnot only in node.js but in browser too.\n\n## usage\n\n```js\nvar inherits = require('inherits');\n// then use exactly as the standard one\n```\n\n## note on version ~1.0\n\nVersion ~1.0 had completely different motivation and is not compatible\nneither with 2.0 nor with standard node.js `inherits`.\n\nIf you are using version ~1.0 and planning to switch to ~2.0, be\ncareful:\n\n* new version uses `super_` instead of `super` for referencing\n superclass\n* new version overwrites current prototype while old one preserves any\n existing fields on it\n",
|
||||
"readmeFilename": "README.md",
|
||||
"bugs": {
|
||||
"url": "https://github.com/isaacs/inherits/issues"
|
||||
},
|
||||
"homepage": "https://github.com/isaacs/inherits",
|
||||
"_id": "inherits@2.0.1",
|
||||
"_from": "inherits@2"
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
var inherits = require('./inherits.js')
|
||||
var assert = require('assert')
|
||||
|
||||
function test(c) {
|
||||
assert(c.constructor === Child)
|
||||
assert(c.constructor.super_ === Parent)
|
||||
assert(Object.getPrototypeOf(c) === Child.prototype)
|
||||
assert(Object.getPrototypeOf(Object.getPrototypeOf(c)) === Parent.prototype)
|
||||
assert(c instanceof Child)
|
||||
assert(c instanceof Parent)
|
||||
}
|
||||
|
||||
function Child() {
|
||||
Parent.call(this)
|
||||
test(this)
|
||||
}
|
||||
|
||||
function Parent() {}
|
||||
|
||||
inherits(Child, Parent)
|
||||
|
||||
var c = new Child
|
||||
test(c)
|
||||
|
||||
console.log('ok')
|
||||
+1
@@ -0,0 +1 @@
|
||||
node_modules
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
Copyright 2009, 2010, 2011 Isaac Z. Schlueter.
|
||||
All rights reserved.
|
||||
|
||||
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.
|
||||
+218
@@ -0,0 +1,218 @@
|
||||
# minimatch
|
||||
|
||||
A minimal matching utility.
|
||||
|
||||
[](http://travis-ci.org/isaacs/minimatch)
|
||||
|
||||
|
||||
This is the matching library used internally by npm.
|
||||
|
||||
Eventually, it will replace the C binding in node-glob.
|
||||
|
||||
It works by converting glob expressions into JavaScript `RegExp`
|
||||
objects.
|
||||
|
||||
## Usage
|
||||
|
||||
```javascript
|
||||
var minimatch = require("minimatch")
|
||||
|
||||
minimatch("bar.foo", "*.foo") // true!
|
||||
minimatch("bar.foo", "*.bar") // false!
|
||||
minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy!
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
Supports these glob features:
|
||||
|
||||
* Brace Expansion
|
||||
* Extended glob matching
|
||||
* "Globstar" `**` matching
|
||||
|
||||
See:
|
||||
|
||||
* `man sh`
|
||||
* `man bash`
|
||||
* `man 3 fnmatch`
|
||||
* `man 5 gitignore`
|
||||
|
||||
## Minimatch Class
|
||||
|
||||
Create a minimatch object by instanting the `minimatch.Minimatch` class.
|
||||
|
||||
```javascript
|
||||
var Minimatch = require("minimatch").Minimatch
|
||||
var mm = new Minimatch(pattern, options)
|
||||
```
|
||||
|
||||
### Properties
|
||||
|
||||
* `pattern` The original pattern the minimatch object represents.
|
||||
* `options` The options supplied to the constructor.
|
||||
* `set` A 2-dimensional array of regexp or string expressions.
|
||||
Each row in the
|
||||
array corresponds to a brace-expanded pattern. Each item in the row
|
||||
corresponds to a single path-part. For example, the pattern
|
||||
`{a,b/c}/d` would expand to a set of patterns like:
|
||||
|
||||
[ [ a, d ]
|
||||
, [ b, c, d ] ]
|
||||
|
||||
If a portion of the pattern doesn't have any "magic" in it
|
||||
(that is, it's something like `"foo"` rather than `fo*o?`), then it
|
||||
will be left as a string rather than converted to a regular
|
||||
expression.
|
||||
|
||||
* `regexp` Created by the `makeRe` method. A single regular expression
|
||||
expressing the entire pattern. This is useful in cases where you wish
|
||||
to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled.
|
||||
* `negate` True if the pattern is negated.
|
||||
* `comment` True if the pattern is a comment.
|
||||
* `empty` True if the pattern is `""`.
|
||||
|
||||
### Methods
|
||||
|
||||
* `makeRe` Generate the `regexp` member if necessary, and return it.
|
||||
Will return `false` if the pattern is invalid.
|
||||
* `match(fname)` Return true if the filename matches the pattern, or
|
||||
false otherwise.
|
||||
* `matchOne(fileArray, patternArray, partial)` Take a `/`-split
|
||||
filename, and match it against a single row in the `regExpSet`. This
|
||||
method is mainly for internal use, but is exposed so that it can be
|
||||
used by a glob-walker that needs to avoid excessive filesystem calls.
|
||||
|
||||
All other methods are internal, and will be called as necessary.
|
||||
|
||||
## Functions
|
||||
|
||||
The top-level exported function has a `cache` property, which is an LRU
|
||||
cache set to store 100 items. So, calling these methods repeatedly
|
||||
with the same pattern and options will use the same Minimatch object,
|
||||
saving the cost of parsing it multiple times.
|
||||
|
||||
### minimatch(path, pattern, options)
|
||||
|
||||
Main export. Tests a path against the pattern using the options.
|
||||
|
||||
```javascript
|
||||
var isJS = minimatch(file, "*.js", { matchBase: true })
|
||||
```
|
||||
|
||||
### minimatch.filter(pattern, options)
|
||||
|
||||
Returns a function that tests its
|
||||
supplied argument, suitable for use with `Array.filter`. Example:
|
||||
|
||||
```javascript
|
||||
var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true}))
|
||||
```
|
||||
|
||||
### minimatch.match(list, pattern, options)
|
||||
|
||||
Match against the list of
|
||||
files, in the style of fnmatch or glob. If nothing is matched, and
|
||||
options.nonull is set, then return a list containing the pattern itself.
|
||||
|
||||
```javascript
|
||||
var javascripts = minimatch.match(fileList, "*.js", {matchBase: true}))
|
||||
```
|
||||
|
||||
### minimatch.makeRe(pattern, options)
|
||||
|
||||
Make a regular expression object from the pattern.
|
||||
|
||||
## Options
|
||||
|
||||
All options are `false` by default.
|
||||
|
||||
### debug
|
||||
|
||||
Dump a ton of stuff to stderr.
|
||||
|
||||
### nobrace
|
||||
|
||||
Do not expand `{a,b}` and `{1..3}` brace sets.
|
||||
|
||||
### noglobstar
|
||||
|
||||
Disable `**` matching against multiple folder names.
|
||||
|
||||
### dot
|
||||
|
||||
Allow patterns to match filenames starting with a period, even if
|
||||
the pattern does not explicitly have a period in that spot.
|
||||
|
||||
Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot`
|
||||
is set.
|
||||
|
||||
### noext
|
||||
|
||||
Disable "extglob" style patterns like `+(a|b)`.
|
||||
|
||||
### nocase
|
||||
|
||||
Perform a case-insensitive match.
|
||||
|
||||
### nonull
|
||||
|
||||
When a match is not found by `minimatch.match`, return a list containing
|
||||
the pattern itself. When set, an empty list is returned if there are
|
||||
no matches.
|
||||
|
||||
### matchBase
|
||||
|
||||
If set, then patterns without slashes will be matched
|
||||
against the basename of the path if it contains slashes. For example,
|
||||
`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`.
|
||||
|
||||
### nocomment
|
||||
|
||||
Suppress the behavior of treating `#` at the start of a pattern as a
|
||||
comment.
|
||||
|
||||
### nonegate
|
||||
|
||||
Suppress the behavior of treating a leading `!` character as negation.
|
||||
|
||||
### flipNegate
|
||||
|
||||
Returns from negate expressions the same as if they were not negated.
|
||||
(Ie, true on a hit, false on a miss.)
|
||||
|
||||
|
||||
## Comparisons to other fnmatch/glob implementations
|
||||
|
||||
While strict compliance with the existing standards is a worthwhile
|
||||
goal, some discrepancies exist between minimatch and other
|
||||
implementations, and are intentional.
|
||||
|
||||
If the pattern starts with a `!` character, then it is negated. Set the
|
||||
`nonegate` flag to suppress this behavior, and treat leading `!`
|
||||
characters normally. This is perhaps relevant if you wish to start the
|
||||
pattern with a negative extglob pattern like `!(a|B)`. Multiple `!`
|
||||
characters at the start of a pattern will negate the pattern multiple
|
||||
times.
|
||||
|
||||
If a pattern starts with `#`, then it is treated as a comment, and
|
||||
will not match anything. Use `\#` to match a literal `#` at the
|
||||
start of a line, or set the `nocomment` flag to suppress this behavior.
|
||||
|
||||
The double-star character `**` is supported by default, unless the
|
||||
`noglobstar` flag is set. This is supported in the manner of bsdglob
|
||||
and bash 4.1, where `**` only has special significance if it is the only
|
||||
thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but
|
||||
`a/**b` will not.
|
||||
|
||||
If an escaped pattern has no matches, and the `nonull` flag is set,
|
||||
then minimatch.match returns the pattern as-provided, rather than
|
||||
interpreting the character escapes. For example,
|
||||
`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than
|
||||
`"*a?"`. This is akin to setting the `nullglob` option in bash, except
|
||||
that it does not resolve escaped pattern characters.
|
||||
|
||||
If brace expansion is not disabled, then it is performed before any
|
||||
other interpretation of the glob pattern. Thus, a pattern like
|
||||
`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded
|
||||
**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are
|
||||
checked for validity. Since those two are valid, matching proceeds.
|
||||
+1055
File diff suppressed because it is too large.
Load diff
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
/node_modules
|
||||
Generated
Vendored
+14
@@ -0,0 +1,14 @@
|
||||
# Authors, sorted by whether or not they are me
|
||||
Isaac Z. Schlueter <i@izs.me>
|
||||
Brian Cottingham <spiffytech@gmail.com>
|
||||
Carlos Brito Lage <carlos@carloslage.net>
|
||||
Jesse Dailey <jesse.dailey@gmail.com>
|
||||
Kevin O'Hara <kevinohara80@gmail.com>
|
||||
Marco Rogers <marco.rogers@gmail.com>
|
||||
Mark Cavage <mcavage@gmail.com>
|
||||
Marko Mikulicic <marko.mikulicic@isti.cnr.it>
|
||||
Nathan Rajlich <nathan@tootallnate.net>
|
||||
Satheesh Natesan <snateshan@myspace-inc.com>
|
||||
Trent Mick <trentm@gmail.com>
|
||||
ashleybrener <ashley@starlogik.com>
|
||||
n4kz <n4kz@n4kz.com>
|
||||
Generated
Vendored
+23
@@ -0,0 +1,23 @@
|
||||
Copyright 2009, 2010, 2011 Isaac Z. Schlueter.
|
||||
All rights reserved.
|
||||
|
||||
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.
|
||||
Generated
Vendored
+97
@@ -0,0 +1,97 @@
|
||||
# lru cache
|
||||
|
||||
A cache object that deletes the least-recently-used items.
|
||||
|
||||
## Usage:
|
||||
|
||||
```javascript
|
||||
var LRU = require("lru-cache")
|
||||
, options = { max: 500
|
||||
, length: function (n) { return n * 2 }
|
||||
, dispose: function (key, n) { n.close() }
|
||||
, maxAge: 1000 * 60 * 60 }
|
||||
, cache = LRU(options)
|
||||
, otherCache = LRU(50) // sets just the max size
|
||||
|
||||
cache.set("key", "value")
|
||||
cache.get("key") // "value"
|
||||
|
||||
cache.reset() // empty the cache
|
||||
```
|
||||
|
||||
If you put more stuff in it, then items will fall out.
|
||||
|
||||
If you try to put an oversized thing in it, then it'll fall out right
|
||||
away.
|
||||
|
||||
## Options
|
||||
|
||||
* `max` The maximum size of the cache, checked by applying the length
|
||||
function to all values in the cache. Not setting this is kind of
|
||||
silly, since that's the whole purpose of this lib, but it defaults
|
||||
to `Infinity`.
|
||||
* `maxAge` Maximum age in ms. Items are not pro-actively pruned out
|
||||
as they age, but if you try to get an item that is too old, it'll
|
||||
drop it and return undefined instead of giving it to you.
|
||||
* `length` Function that is used to calculate the length of stored
|
||||
items. If you're storing strings or buffers, then you probably want
|
||||
to do something like `function(n){return n.length}`. The default is
|
||||
`function(n){return 1}`, which is fine if you want to store `n`
|
||||
like-sized things.
|
||||
* `dispose` Function that is called on items when they are dropped
|
||||
from the cache. This can be handy if you want to close file
|
||||
descriptors or do other cleanup tasks when items are no longer
|
||||
accessible. Called with `key, value`. It's called *before*
|
||||
actually removing the item from the internal cache, so if you want
|
||||
to immediately put it back in, you'll have to do that in a
|
||||
`nextTick` or `setTimeout` callback or it won't do anything.
|
||||
* `stale` By default, if you set a `maxAge`, it'll only actually pull
|
||||
stale items out of the cache when you `get(key)`. (That is, it's
|
||||
not pre-emptively doing a `setTimeout` or anything.) If you set
|
||||
`stale:true`, it'll return the stale value before deleting it. If
|
||||
you don't set this, then it'll return `undefined` when you try to
|
||||
get a stale entry, as if it had already been deleted.
|
||||
|
||||
## API
|
||||
|
||||
* `set(key, value)`
|
||||
* `get(key) => value`
|
||||
|
||||
Both of these will update the "recently used"-ness of the key.
|
||||
They do what you think.
|
||||
|
||||
* `peek(key)`
|
||||
|
||||
Returns the key value (or `undefined` if not found) without
|
||||
updating the "recently used"-ness of the key.
|
||||
|
||||
(If you find yourself using this a lot, you *might* be using the
|
||||
wrong sort of data structure, but there are some use cases where
|
||||
it's handy.)
|
||||
|
||||
* `del(key)`
|
||||
|
||||
Deletes a key out of the cache.
|
||||
|
||||
* `reset()`
|
||||
|
||||
Clear the cache entirely, throwing away all values.
|
||||
|
||||
* `has(key)`
|
||||
|
||||
Check if a key is in the cache, without updating the recent-ness
|
||||
or deleting it for being stale.
|
||||
|
||||
* `forEach(function(value,key,cache), [thisp])`
|
||||
|
||||
Just like `Array.prototype.forEach`. Iterates over all the keys
|
||||
in the cache, in order of recent-ness. (Ie, more recently used
|
||||
items are iterated over first.)
|
||||
|
||||
* `keys()`
|
||||
|
||||
Return an array of the keys in the cache.
|
||||
|
||||
* `values()`
|
||||
|
||||
Return an array of the values in the cache.
|
||||
Generated
Vendored
+252
@@ -0,0 +1,252 @@
|
||||
;(function () { // closure for web browsers
|
||||
|
||||
if (typeof module === 'object' && module.exports) {
|
||||
module.exports = LRUCache
|
||||
} else {
|
||||
// just set the global for non-node platforms.
|
||||
this.LRUCache = LRUCache
|
||||
}
|
||||
|
||||
function hOP (obj, key) {
|
||||
return Object.prototype.hasOwnProperty.call(obj, key)
|
||||
}
|
||||
|
||||
function naiveLength () { return 1 }
|
||||
|
||||
function LRUCache (options) {
|
||||
if (!(this instanceof LRUCache))
|
||||
return new LRUCache(options)
|
||||
|
||||
if (typeof options === 'number')
|
||||
options = { max: options }
|
||||
|
||||
if (!options)
|
||||
options = {}
|
||||
|
||||
this._max = options.max
|
||||
// Kind of weird to have a default max of Infinity, but oh well.
|
||||
if (!this._max || !(typeof this._max === "number") || this._max <= 0 )
|
||||
this._max = Infinity
|
||||
|
||||
this._lengthCalculator = options.length || naiveLength
|
||||
if (typeof this._lengthCalculator !== "function")
|
||||
this._lengthCalculator = naiveLength
|
||||
|
||||
this._allowStale = options.stale || false
|
||||
this._maxAge = options.maxAge || null
|
||||
this._dispose = options.dispose
|
||||
this.reset()
|
||||
}
|
||||
|
||||
// resize the cache when the max changes.
|
||||
Object.defineProperty(LRUCache.prototype, "max",
|
||||
{ set : function (mL) {
|
||||
if (!mL || !(typeof mL === "number") || mL <= 0 ) mL = Infinity
|
||||
this._max = mL
|
||||
if (this._length > this._max) trim(this)
|
||||
}
|
||||
, get : function () { return this._max }
|
||||
, enumerable : true
|
||||
})
|
||||
|
||||
// resize the cache when the lengthCalculator changes.
|
||||
Object.defineProperty(LRUCache.prototype, "lengthCalculator",
|
||||
{ set : function (lC) {
|
||||
if (typeof lC !== "function") {
|
||||
this._lengthCalculator = naiveLength
|
||||
this._length = this._itemCount
|
||||
for (var key in this._cache) {
|
||||
this._cache[key].length = 1
|
||||
}
|
||||
} else {
|
||||
this._lengthCalculator = lC
|
||||
this._length = 0
|
||||
for (var key in this._cache) {
|
||||
this._cache[key].length = this._lengthCalculator(this._cache[key].value)
|
||||
this._length += this._cache[key].length
|
||||
}
|
||||
}
|
||||
|
||||
if (this._length > this._max) trim(this)
|
||||
}
|
||||
, get : function () { return this._lengthCalculator }
|
||||
, enumerable : true
|
||||
})
|
||||
|
||||
Object.defineProperty(LRUCache.prototype, "length",
|
||||
{ get : function () { return this._length }
|
||||
, enumerable : true
|
||||
})
|
||||
|
||||
|
||||
Object.defineProperty(LRUCache.prototype, "itemCount",
|
||||
{ get : function () { return this._itemCount }
|
||||
, enumerable : true
|
||||
})
|
||||
|
||||
LRUCache.prototype.forEach = function (fn, thisp) {
|
||||
thisp = thisp || this
|
||||
var i = 0;
|
||||
for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) if (this._lruList[k]) {
|
||||
i++
|
||||
var hit = this._lruList[k]
|
||||
if (this._maxAge && (Date.now() - hit.now > this._maxAge)) {
|
||||
del(this, hit)
|
||||
if (!this._allowStale) hit = undefined
|
||||
}
|
||||
if (hit) {
|
||||
fn.call(thisp, hit.value, hit.key, this)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LRUCache.prototype.keys = function () {
|
||||
var keys = new Array(this._itemCount)
|
||||
var i = 0
|
||||
for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) if (this._lruList[k]) {
|
||||
var hit = this._lruList[k]
|
||||
keys[i++] = hit.key
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
LRUCache.prototype.values = function () {
|
||||
var values = new Array(this._itemCount)
|
||||
var i = 0
|
||||
for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) if (this._lruList[k]) {
|
||||
var hit = this._lruList[k]
|
||||
values[i++] = hit.value
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
LRUCache.prototype.reset = function () {
|
||||
if (this._dispose && this._cache) {
|
||||
for (var k in this._cache) {
|
||||
this._dispose(k, this._cache[k].value)
|
||||
}
|
||||
}
|
||||
|
||||
this._cache = Object.create(null) // hash of items by key
|
||||
this._lruList = Object.create(null) // list of items in order of use recency
|
||||
this._mru = 0 // most recently used
|
||||
this._lru = 0 // least recently used
|
||||
this._length = 0 // number of items in the list
|
||||
this._itemCount = 0
|
||||
}
|
||||
|
||||
// Provided for debugging/dev purposes only. No promises whatsoever that
|
||||
// this API stays stable.
|
||||
LRUCache.prototype.dump = function () {
|
||||
return this._cache
|
||||
}
|
||||
|
||||
LRUCache.prototype.dumpLru = function () {
|
||||
return this._lruList
|
||||
}
|
||||
|
||||
LRUCache.prototype.set = function (key, value) {
|
||||
if (hOP(this._cache, key)) {
|
||||
// dispose of the old one before overwriting
|
||||
if (this._dispose) this._dispose(key, this._cache[key].value)
|
||||
if (this._maxAge) this._cache[key].now = Date.now()
|
||||
this._cache[key].value = value
|
||||
this.get(key)
|
||||
return true
|
||||
}
|
||||
|
||||
var len = this._lengthCalculator(value)
|
||||
var age = this._maxAge ? Date.now() : 0
|
||||
var hit = new Entry(key, value, this._mru++, len, age)
|
||||
|
||||
// oversized objects fall out of cache automatically.
|
||||
if (hit.length > this._max) {
|
||||
if (this._dispose) this._dispose(key, value)
|
||||
return false
|
||||
}
|
||||
|
||||
this._length += hit.length
|
||||
this._lruList[hit.lu] = this._cache[key] = hit
|
||||
this._itemCount ++
|
||||
|
||||
if (this._length > this._max) trim(this)
|
||||
return true
|
||||
}
|
||||
|
||||
LRUCache.prototype.has = function (key) {
|
||||
if (!hOP(this._cache, key)) return false
|
||||
var hit = this._cache[key]
|
||||
if (this._maxAge && (Date.now() - hit.now > this._maxAge)) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
LRUCache.prototype.get = function (key) {
|
||||
return get(this, key, true)
|
||||
}
|
||||
|
||||
LRUCache.prototype.peek = function (key) {
|
||||
return get(this, key, false)
|
||||
}
|
||||
|
||||
LRUCache.prototype.pop = function () {
|
||||
var hit = this._lruList[this._lru]
|
||||
del(this, hit)
|
||||
return hit || null
|
||||
}
|
||||
|
||||
LRUCache.prototype.del = function (key) {
|
||||
del(this, this._cache[key])
|
||||
}
|
||||
|
||||
function get (self, key, doUse) {
|
||||
var hit = self._cache[key]
|
||||
if (hit) {
|
||||
if (self._maxAge && (Date.now() - hit.now > self._maxAge)) {
|
||||
del(self, hit)
|
||||
if (!self._allowStale) hit = undefined
|
||||
} else {
|
||||
if (doUse) use(self, hit)
|
||||
}
|
||||
if (hit) hit = hit.value
|
||||
}
|
||||
return hit
|
||||
}
|
||||
|
||||
function use (self, hit) {
|
||||
shiftLU(self, hit)
|
||||
hit.lu = self._mru ++
|
||||
self._lruList[hit.lu] = hit
|
||||
}
|
||||
|
||||
function trim (self) {
|
||||
while (self._lru < self._mru && self._length > self._max)
|
||||
del(self, self._lruList[self._lru])
|
||||
}
|
||||
|
||||
function shiftLU (self, hit) {
|
||||
delete self._lruList[ hit.lu ]
|
||||
while (self._lru < self._mru && !self._lruList[self._lru]) self._lru ++
|
||||
}
|
||||
|
||||
function del (self, hit) {
|
||||
if (hit) {
|
||||
if (self._dispose) self._dispose(hit.key, hit.value)
|
||||
self._length -= hit.length
|
||||
self._itemCount --
|
||||
delete self._cache[ hit.key ]
|
||||
shiftLU(self, hit)
|
||||
}
|
||||
}
|
||||
|
||||
// classy, since V8 prefers predictable objects.
|
||||
function Entry (key, value, lu, length, now) {
|
||||
this.key = key
|
||||
this.value = value
|
||||
this.lu = lu
|
||||
this.length = length
|
||||
this.now = now
|
||||
}
|
||||
|
||||
})()
|
||||
Generated
Vendored
+33
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"name": "lru-cache",
|
||||
"description": "A cache object that deletes the least-recently-used items.",
|
||||
"version": "2.5.0",
|
||||
"author": {
|
||||
"name": "Isaac Z. Schlueter",
|
||||
"email": "i@izs.me"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "tap test --gc"
|
||||
},
|
||||
"main": "lib/lru-cache.js",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/isaacs/node-lru-cache.git"
|
||||
},
|
||||
"devDependencies": {
|
||||
"tap": "",
|
||||
"weak": ""
|
||||
},
|
||||
"license": {
|
||||
"type": "MIT",
|
||||
"url": "http://github.com/isaacs/node-lru-cache/raw/master/LICENSE"
|
||||
},
|
||||
"readme": "# lru cache\n\nA cache object that deletes the least-recently-used items.\n\n## Usage:\n\n```javascript\nvar LRU = require(\"lru-cache\")\n , options = { max: 500\n , length: function (n) { return n * 2 }\n , dispose: function (key, n) { n.close() }\n , maxAge: 1000 * 60 * 60 }\n , cache = LRU(options)\n , otherCache = LRU(50) // sets just the max size\n\ncache.set(\"key\", \"value\")\ncache.get(\"key\") // \"value\"\n\ncache.reset() // empty the cache\n```\n\nIf you put more stuff in it, then items will fall out.\n\nIf you try to put an oversized thing in it, then it'll fall out right\naway.\n\n## Options\n\n* `max` The maximum size of the cache, checked by applying the length\n function to all values in the cache. Not setting this is kind of\n silly, since that's the whole purpose of this lib, but it defaults\n to `Infinity`.\n* `maxAge` Maximum age in ms. Items are not pro-actively pruned out\n as they age, but if you try to get an item that is too old, it'll\n drop it and return undefined instead of giving it to you.\n* `length` Function that is used to calculate the length of stored\n items. If you're storing strings or buffers, then you probably want\n to do something like `function(n){return n.length}`. The default is\n `function(n){return 1}`, which is fine if you want to store `n`\n like-sized things.\n* `dispose` Function that is called on items when they are dropped\n from the cache. This can be handy if you want to close file\n descriptors or do other cleanup tasks when items are no longer\n accessible. Called with `key, value`. It's called *before*\n actually removing the item from the internal cache, so if you want\n to immediately put it back in, you'll have to do that in a\n `nextTick` or `setTimeout` callback or it won't do anything.\n* `stale` By default, if you set a `maxAge`, it'll only actually pull\n stale items out of the cache when you `get(key)`. (That is, it's\n not pre-emptively doing a `setTimeout` or anything.) If you set\n `stale:true`, it'll return the stale value before deleting it. If\n you don't set this, then it'll return `undefined` when you try to\n get a stale entry, as if it had already been deleted.\n\n## API\n\n* `set(key, value)`\n* `get(key) => value`\n\n Both of these will update the \"recently used\"-ness of the key.\n They do what you think.\n\n* `peek(key)`\n\n Returns the key value (or `undefined` if not found) without\n updating the \"recently used\"-ness of the key.\n\n (If you find yourself using this a lot, you *might* be using the\n wrong sort of data structure, but there are some use cases where\n it's handy.)\n\n* `del(key)`\n\n Deletes a key out of the cache.\n\n* `reset()`\n\n Clear the cache entirely, throwing away all values.\n\n* `has(key)`\n\n Check if a key is in the cache, without updating the recent-ness\n or deleting it for being stale.\n\n* `forEach(function(value,key,cache), [thisp])`\n\n Just like `Array.prototype.forEach`. Iterates over all the keys\n in the cache, in order of recent-ness. (Ie, more recently used\n items are iterated over first.)\n\n* `keys()`\n\n Return an array of the keys in the cache.\n\n* `values()`\n\n Return an array of the values in the cache.\n",
|
||||
"readmeFilename": "README.md",
|
||||
"bugs": {
|
||||
"url": "https://github.com/isaacs/node-lru-cache/issues"
|
||||
},
|
||||
"homepage": "https://github.com/isaacs/node-lru-cache",
|
||||
"_id": "lru-cache@2.5.0",
|
||||
"_from": "lru-cache@2"
|
||||
}
|
||||
Generated
Vendored
+369
@@ -0,0 +1,369 @@
|
||||
var test = require("tap").test
|
||||
, LRU = require("../")
|
||||
|
||||
test("basic", function (t) {
|
||||
var cache = new LRU({max: 10})
|
||||
cache.set("key", "value")
|
||||
t.equal(cache.get("key"), "value")
|
||||
t.equal(cache.get("nada"), undefined)
|
||||
t.equal(cache.length, 1)
|
||||
t.equal(cache.max, 10)
|
||||
t.end()
|
||||
})
|
||||
|
||||
test("least recently set", function (t) {
|
||||
var cache = new LRU(2)
|
||||
cache.set("a", "A")
|
||||
cache.set("b", "B")
|
||||
cache.set("c", "C")
|
||||
t.equal(cache.get("c"), "C")
|
||||
t.equal(cache.get("b"), "B")
|
||||
t.equal(cache.get("a"), undefined)
|
||||
t.end()
|
||||
})
|
||||
|
||||
test("lru recently gotten", function (t) {
|
||||
var cache = new LRU(2)
|
||||
cache.set("a", "A")
|
||||
cache.set("b", "B")
|
||||
cache.get("a")
|
||||
cache.set("c", "C")
|
||||
t.equal(cache.get("c"), "C")
|
||||
t.equal(cache.get("b"), undefined)
|
||||
t.equal(cache.get("a"), "A")
|
||||
t.end()
|
||||
})
|
||||
|
||||
test("del", function (t) {
|
||||
var cache = new LRU(2)
|
||||
cache.set("a", "A")
|
||||
cache.del("a")
|
||||
t.equal(cache.get("a"), undefined)
|
||||
t.end()
|
||||
})
|
||||
|
||||
test("max", function (t) {
|
||||
var cache = new LRU(3)
|
||||
|
||||
// test changing the max, verify that the LRU items get dropped.
|
||||
cache.max = 100
|
||||
for (var i = 0; i < 100; i ++) cache.set(i, i)
|
||||
t.equal(cache.length, 100)
|
||||
for (var i = 0; i < 100; i ++) {
|
||||
t.equal(cache.get(i), i)
|
||||
}
|
||||
cache.max = 3
|
||||
t.equal(cache.length, 3)
|
||||
for (var i = 0; i < 97; i ++) {
|
||||
t.equal(cache.get(i), undefined)
|
||||
}
|
||||
for (var i = 98; i < 100; i ++) {
|
||||
t.equal(cache.get(i), i)
|
||||
}
|
||||
|
||||
// now remove the max restriction, and try again.
|
||||
cache.max = "hello"
|
||||
for (var i = 0; i < 100; i ++) cache.set(i, i)
|
||||
t.equal(cache.length, 100)
|
||||
for (var i = 0; i < 100; i ++) {
|
||||
t.equal(cache.get(i), i)
|
||||
}
|
||||
// should trigger an immediate resize
|
||||
cache.max = 3
|
||||
t.equal(cache.length, 3)
|
||||
for (var i = 0; i < 97; i ++) {
|
||||
t.equal(cache.get(i), undefined)
|
||||
}
|
||||
for (var i = 98; i < 100; i ++) {
|
||||
t.equal(cache.get(i), i)
|
||||
}
|
||||
t.end()
|
||||
})
|
||||
|
||||
test("reset", function (t) {
|
||||
var cache = new LRU(10)
|
||||
cache.set("a", "A")
|
||||
cache.set("b", "B")
|
||||
cache.reset()
|
||||
t.equal(cache.length, 0)
|
||||
t.equal(cache.max, 10)
|
||||
t.equal(cache.get("a"), undefined)
|
||||
t.equal(cache.get("b"), undefined)
|
||||
t.end()
|
||||
})
|
||||
|
||||
|
||||
// Note: `<cache>.dump()` is a debugging tool only. No guarantees are made
|
||||
// about the format/layout of the response.
|
||||
test("dump", function (t) {
|
||||
var cache = new LRU(10)
|
||||
var d = cache.dump();
|
||||
t.equal(Object.keys(d).length, 0, "nothing in dump for empty cache")
|
||||
cache.set("a", "A")
|
||||
var d = cache.dump() // { a: { key: "a", value: "A", lu: 0 } }
|
||||
t.ok(d.a)
|
||||
t.equal(d.a.key, "a")
|
||||
t.equal(d.a.value, "A")
|
||||
t.equal(d.a.lu, 0)
|
||||
|
||||
cache.set("b", "B")
|
||||
cache.get("b")
|
||||
d = cache.dump()
|
||||
t.ok(d.b)
|
||||
t.equal(d.b.key, "b")
|
||||
t.equal(d.b.value, "B")
|
||||
t.equal(d.b.lu, 2)
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
|
||||
test("basic with weighed length", function (t) {
|
||||
var cache = new LRU({
|
||||
max: 100,
|
||||
length: function (item) { return item.size }
|
||||
})
|
||||
cache.set("key", {val: "value", size: 50})
|
||||
t.equal(cache.get("key").val, "value")
|
||||
t.equal(cache.get("nada"), undefined)
|
||||
t.equal(cache.lengthCalculator(cache.get("key")), 50)
|
||||
t.equal(cache.length, 50)
|
||||
t.equal(cache.max, 100)
|
||||
t.end()
|
||||
})
|
||||
|
||||
|
||||
test("weighed length item too large", function (t) {
|
||||
var cache = new LRU({
|
||||
max: 10,
|
||||
length: function (item) { return item.size }
|
||||
})
|
||||
t.equal(cache.max, 10)
|
||||
|
||||
// should fall out immediately
|
||||
cache.set("key", {val: "value", size: 50})
|
||||
|
||||
t.equal(cache.length, 0)
|
||||
t.equal(cache.get("key"), undefined)
|
||||
t.end()
|
||||
})
|
||||
|
||||
test("least recently set with weighed length", function (t) {
|
||||
var cache = new LRU({
|
||||
max:8,
|
||||
length: function (item) { return item.length }
|
||||
})
|
||||
cache.set("a", "A")
|
||||
cache.set("b", "BB")
|
||||
cache.set("c", "CCC")
|
||||
cache.set("d", "DDDD")
|
||||
t.equal(cache.get("d"), "DDDD")
|
||||
t.equal(cache.get("c"), "CCC")
|
||||
t.equal(cache.get("b"), undefined)
|
||||
t.equal(cache.get("a"), undefined)
|
||||
t.end()
|
||||
})
|
||||
|
||||
test("lru recently gotten with weighed length", function (t) {
|
||||
var cache = new LRU({
|
||||
max: 8,
|
||||
length: function (item) { return item.length }
|
||||
})
|
||||
cache.set("a", "A")
|
||||
cache.set("b", "BB")
|
||||
cache.set("c", "CCC")
|
||||
cache.get("a")
|
||||
cache.get("b")
|
||||
cache.set("d", "DDDD")
|
||||
t.equal(cache.get("c"), undefined)
|
||||
t.equal(cache.get("d"), "DDDD")
|
||||
t.equal(cache.get("b"), "BB")
|
||||
t.equal(cache.get("a"), "A")
|
||||
t.end()
|
||||
})
|
||||
|
||||
test("set returns proper booleans", function(t) {
|
||||
var cache = new LRU({
|
||||
max: 5,
|
||||
length: function (item) { return item.length }
|
||||
})
|
||||
|
||||
t.equal(cache.set("a", "A"), true)
|
||||
|
||||
// should return false for max exceeded
|
||||
t.equal(cache.set("b", "donuts"), false)
|
||||
|
||||
t.equal(cache.set("b", "B"), true)
|
||||
t.equal(cache.set("c", "CCCC"), true)
|
||||
t.end()
|
||||
})
|
||||
|
||||
test("drop the old items", function(t) {
|
||||
var cache = new LRU({
|
||||
max: 5,
|
||||
maxAge: 50
|
||||
})
|
||||
|
||||
cache.set("a", "A")
|
||||
|
||||
setTimeout(function () {
|
||||
cache.set("b", "b")
|
||||
t.equal(cache.get("a"), "A")
|
||||
}, 25)
|
||||
|
||||
setTimeout(function () {
|
||||
cache.set("c", "C")
|
||||
// timed out
|
||||
t.notOk(cache.get("a"))
|
||||
}, 60)
|
||||
|
||||
setTimeout(function () {
|
||||
t.notOk(cache.get("b"))
|
||||
t.equal(cache.get("c"), "C")
|
||||
}, 90)
|
||||
|
||||
setTimeout(function () {
|
||||
t.notOk(cache.get("c"))
|
||||
t.end()
|
||||
}, 155)
|
||||
})
|
||||
|
||||
test("disposal function", function(t) {
|
||||
var disposed = false
|
||||
var cache = new LRU({
|
||||
max: 1,
|
||||
dispose: function (k, n) {
|
||||
disposed = n
|
||||
}
|
||||
})
|
||||
|
||||
cache.set(1, 1)
|
||||
cache.set(2, 2)
|
||||
t.equal(disposed, 1)
|
||||
cache.set(3, 3)
|
||||
t.equal(disposed, 2)
|
||||
cache.reset()
|
||||
t.equal(disposed, 3)
|
||||
t.end()
|
||||
})
|
||||
|
||||
test("disposal function on too big of item", function(t) {
|
||||
var disposed = false
|
||||
var cache = new LRU({
|
||||
max: 1,
|
||||
length: function (k) {
|
||||
return k.length
|
||||
},
|
||||
dispose: function (k, n) {
|
||||
disposed = n
|
||||
}
|
||||
})
|
||||
var obj = [ 1, 2 ]
|
||||
|
||||
t.equal(disposed, false)
|
||||
cache.set("obj", obj)
|
||||
t.equal(disposed, obj)
|
||||
t.end()
|
||||
})
|
||||
|
||||
test("has()", function(t) {
|
||||
var cache = new LRU({
|
||||
max: 1,
|
||||
maxAge: 10
|
||||
})
|
||||
|
||||
cache.set('foo', 'bar')
|
||||
t.equal(cache.has('foo'), true)
|
||||
cache.set('blu', 'baz')
|
||||
t.equal(cache.has('foo'), false)
|
||||
t.equal(cache.has('blu'), true)
|
||||
setTimeout(function() {
|
||||
t.equal(cache.has('blu'), false)
|
||||
t.end()
|
||||
}, 15)
|
||||
})
|
||||
|
||||
test("stale", function(t) {
|
||||
var cache = new LRU({
|
||||
maxAge: 10,
|
||||
stale: true
|
||||
})
|
||||
|
||||
cache.set('foo', 'bar')
|
||||
t.equal(cache.get('foo'), 'bar')
|
||||
t.equal(cache.has('foo'), true)
|
||||
setTimeout(function() {
|
||||
t.equal(cache.has('foo'), false)
|
||||
t.equal(cache.get('foo'), 'bar')
|
||||
t.equal(cache.get('foo'), undefined)
|
||||
t.end()
|
||||
}, 15)
|
||||
})
|
||||
|
||||
test("lru update via set", function(t) {
|
||||
var cache = LRU({ max: 2 });
|
||||
|
||||
cache.set('foo', 1);
|
||||
cache.set('bar', 2);
|
||||
cache.del('bar');
|
||||
cache.set('baz', 3);
|
||||
cache.set('qux', 4);
|
||||
|
||||
t.equal(cache.get('foo'), undefined)
|
||||
t.equal(cache.get('bar'), undefined)
|
||||
t.equal(cache.get('baz'), 3)
|
||||
t.equal(cache.get('qux'), 4)
|
||||
t.end()
|
||||
})
|
||||
|
||||
test("least recently set w/ peek", function (t) {
|
||||
var cache = new LRU(2)
|
||||
cache.set("a", "A")
|
||||
cache.set("b", "B")
|
||||
t.equal(cache.peek("a"), "A")
|
||||
cache.set("c", "C")
|
||||
t.equal(cache.get("c"), "C")
|
||||
t.equal(cache.get("b"), "B")
|
||||
t.equal(cache.get("a"), undefined)
|
||||
t.end()
|
||||
})
|
||||
|
||||
test("pop the least used item", function (t) {
|
||||
var cache = new LRU(3)
|
||||
, last
|
||||
|
||||
cache.set("a", "A")
|
||||
cache.set("b", "B")
|
||||
cache.set("c", "C")
|
||||
|
||||
t.equal(cache.length, 3)
|
||||
t.equal(cache.max, 3)
|
||||
|
||||
// Ensure we pop a, c, b
|
||||
cache.get("b", "B")
|
||||
|
||||
last = cache.pop()
|
||||
t.equal(last.key, "a")
|
||||
t.equal(last.value, "A")
|
||||
t.equal(cache.length, 2)
|
||||
t.equal(cache.max, 3)
|
||||
|
||||
last = cache.pop()
|
||||
t.equal(last.key, "c")
|
||||
t.equal(last.value, "C")
|
||||
t.equal(cache.length, 1)
|
||||
t.equal(cache.max, 3)
|
||||
|
||||
last = cache.pop()
|
||||
t.equal(last.key, "b")
|
||||
t.equal(last.value, "B")
|
||||
t.equal(cache.length, 0)
|
||||
t.equal(cache.max, 3)
|
||||
|
||||
last = cache.pop()
|
||||
t.equal(last, null)
|
||||
t.equal(cache.length, 0)
|
||||
t.equal(cache.max, 3)
|
||||
|
||||
t.end()
|
||||
})
|
||||
Generated
Vendored
+52
@@ -0,0 +1,52 @@
|
||||
var test = require('tap').test
|
||||
var LRU = require('../')
|
||||
|
||||
test('forEach', function (t) {
|
||||
var l = new LRU(5)
|
||||
for (var i = 0; i < 10; i ++) {
|
||||
l.set(i.toString(), i.toString(2))
|
||||
}
|
||||
|
||||
var i = 9
|
||||
l.forEach(function (val, key, cache) {
|
||||
t.equal(cache, l)
|
||||
t.equal(key, i.toString())
|
||||
t.equal(val, i.toString(2))
|
||||
i -= 1
|
||||
})
|
||||
|
||||
// get in order of most recently used
|
||||
l.get(6)
|
||||
l.get(8)
|
||||
|
||||
var order = [ 8, 6, 9, 7, 5 ]
|
||||
var i = 0
|
||||
|
||||
l.forEach(function (val, key, cache) {
|
||||
var j = order[i ++]
|
||||
t.equal(cache, l)
|
||||
t.equal(key, j.toString())
|
||||
t.equal(val, j.toString(2))
|
||||
})
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
test('keys() and values()', function (t) {
|
||||
var l = new LRU(5)
|
||||
for (var i = 0; i < 10; i ++) {
|
||||
l.set(i.toString(), i.toString(2))
|
||||
}
|
||||
|
||||
t.similar(l.keys(), ['9', '8', '7', '6', '5'])
|
||||
t.similar(l.values(), ['1001', '1000', '111', '110', '101'])
|
||||
|
||||
// get in order of most recently used
|
||||
l.get(6)
|
||||
l.get(8)
|
||||
|
||||
t.similar(l.keys(), ['8', '6', '9', '7', '5'])
|
||||
t.similar(l.values(), ['1000', '110', '1001', '111', '101'])
|
||||
|
||||
t.end()
|
||||
})
|
||||
Generated
Vendored
+50
@@ -0,0 +1,50 @@
|
||||
#!/usr/bin/env node --expose_gc
|
||||
|
||||
var weak = require('weak');
|
||||
var test = require('tap').test
|
||||
var LRU = require('../')
|
||||
var l = new LRU({ max: 10 })
|
||||
var refs = 0
|
||||
function X() {
|
||||
refs ++
|
||||
weak(this, deref)
|
||||
}
|
||||
|
||||
function deref() {
|
||||
refs --
|
||||
}
|
||||
|
||||
test('no leaks', function (t) {
|
||||
// fill up the cache
|
||||
for (var i = 0; i < 100; i++) {
|
||||
l.set(i, new X);
|
||||
// throw some gets in there, too.
|
||||
if (i % 2 === 0)
|
||||
l.get(i / 2)
|
||||
}
|
||||
|
||||
gc()
|
||||
|
||||
var start = process.memoryUsage()
|
||||
|
||||
// capture the memory
|
||||
var startRefs = refs
|
||||
|
||||
// do it again, but more
|
||||
for (var i = 0; i < 10000; i++) {
|
||||
l.set(i, new X);
|
||||
// throw some gets in there, too.
|
||||
if (i % 2 === 0)
|
||||
l.get(i / 2)
|
||||
}
|
||||
|
||||
gc()
|
||||
|
||||
var end = process.memoryUsage()
|
||||
t.equal(refs, startRefs, 'no leaky refs')
|
||||
|
||||
console.error('start: %j\n' +
|
||||
'end: %j', start, end);
|
||||
t.pass();
|
||||
t.end();
|
||||
})
|
||||
Generated
Vendored
+27
@@ -0,0 +1,27 @@
|
||||
Copyright (c) Isaac Z. Schlueter ("Author")
|
||||
All rights reserved.
|
||||
|
||||
The BSD License
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
|
||||
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
|
||||
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
|
||||
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
Generated
Vendored
+53
@@ -0,0 +1,53 @@
|
||||
# sigmund
|
||||
|
||||
Quick and dirty signatures for Objects.
|
||||
|
||||
This is like a much faster `deepEquals` comparison, which returns a
|
||||
string key suitable for caches and the like.
|
||||
|
||||
## Usage
|
||||
|
||||
```javascript
|
||||
function doSomething (someObj) {
|
||||
var key = sigmund(someObj, maxDepth) // max depth defaults to 10
|
||||
var cached = cache.get(key)
|
||||
if (cached) return cached)
|
||||
|
||||
var result = expensiveCalculation(someObj)
|
||||
cache.set(key, result)
|
||||
return result
|
||||
}
|
||||
```
|
||||
|
||||
The resulting key will be as unique and reproducible as calling
|
||||
`JSON.stringify` or `util.inspect` on the object, but is much faster.
|
||||
In order to achieve this speed, some differences are glossed over.
|
||||
For example, the object `{0:'foo'}` will be treated identically to the
|
||||
array `['foo']`.
|
||||
|
||||
Also, just as there is no way to summon the soul from the scribblings
|
||||
of a cocain-addled psychoanalyst, there is no way to revive the object
|
||||
from the signature string that sigmund gives you. In fact, it's
|
||||
barely even readable.
|
||||
|
||||
As with `sys.inspect` and `JSON.stringify`, larger objects will
|
||||
produce larger signature strings.
|
||||
|
||||
Because sigmund is a bit less strict than the more thorough
|
||||
alternatives, the strings will be shorter, and also there is a
|
||||
slightly higher chance for collisions. For example, these objects
|
||||
have the same signature:
|
||||
|
||||
var obj1 = {a:'b',c:/def/,g:['h','i',{j:'',k:'l'}]}
|
||||
var obj2 = {a:'b',c:'/def/',g:['h','i','{jkl']}
|
||||
|
||||
Like a good Freudian, sigmund is most effective when you already have
|
||||
some understanding of what you're looking for. It can help you help
|
||||
yourself, but you must be willing to do some work as well.
|
||||
|
||||
Cycles are handled, and cyclical objects are silently omitted (though
|
||||
the key is included in the signature output.)
|
||||
|
||||
The second argument is the maximum depth, which defaults to 10,
|
||||
because that is the maximum object traversal depth covered by most
|
||||
insurance carriers.
|
||||
Loaded 100 of 3159 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user