Likelike online Omoma version
Added modding functions and examples of room specific behavior in (clientMod and serverMod). Basic structures for NPC, semi-permanent objects, room-based soundtrack. Refactor sprite drawing - now called "things" and stored in and objectmaster
parent
6bc17ead3c
commit
f8eb18c202
File diff suppressed because one or more lines are too long
@ -0,0 +1 @@
|
||||
../yamljs/bin/json2yaml
|
@ -0,0 +1 @@
|
||||
../yamljs/bin/yaml2json
|
@ -0,0 +1,185 @@
|
||||
1.0.10 / 2018-02-15
|
||||
------------------
|
||||
|
||||
- Use .concat instead of + for arrays, #122.
|
||||
|
||||
|
||||
1.0.9 / 2016-09-29
|
||||
------------------
|
||||
|
||||
- Rerelease after 1.0.8 - deps cleanup.
|
||||
|
||||
|
||||
1.0.8 / 2016-09-29
|
||||
------------------
|
||||
|
||||
- Maintenance (deps bump, fix node 6.5+ tests, coverage report).
|
||||
|
||||
|
||||
1.0.7 / 2016-03-17
|
||||
------------------
|
||||
|
||||
- Teach `addArgument` to accept string arg names. #97, @tomxtobin.
|
||||
|
||||
|
||||
1.0.6 / 2016-02-06
|
||||
------------------
|
||||
|
||||
- Maintenance: moved to eslint & updated CS.
|
||||
|
||||
|
||||
1.0.5 / 2016-02-05
|
||||
------------------
|
||||
|
||||
- Removed lodash dependency to significantly reduce install size.
|
||||
Thanks to @mourner.
|
||||
|
||||
|
||||
1.0.4 / 2016-01-17
|
||||
------------------
|
||||
|
||||
- Maintenance: lodash update to 4.0.0.
|
||||
|
||||
|
||||
1.0.3 / 2015-10-27
|
||||
------------------
|
||||
|
||||
- Fix parse `=` in args: `--examplepath="C:\myfolder\env=x64"`. #84, @CatWithApple.
|
||||
|
||||
|
||||
1.0.2 / 2015-03-22
|
||||
------------------
|
||||
|
||||
- Relaxed lodash version dependency.
|
||||
|
||||
|
||||
1.0.1 / 2015-02-20
|
||||
------------------
|
||||
|
||||
- Changed dependencies to be compatible with ancient nodejs.
|
||||
|
||||
|
||||
1.0.0 / 2015-02-19
|
||||
------------------
|
||||
|
||||
- Maintenance release.
|
||||
- Replaced `underscore` with `lodash`.
|
||||
- Bumped version to 1.0.0 to better reflect semver meaning.
|
||||
- HISTORY.md -> CHANGELOG.md
|
||||
|
||||
|
||||
0.1.16 / 2013-12-01
|
||||
-------------------
|
||||
|
||||
- Maintenance release. Updated dependencies and docs.
|
||||
|
||||
|
||||
0.1.15 / 2013-05-13
|
||||
-------------------
|
||||
|
||||
- Fixed #55, @trebor89
|
||||
|
||||
|
||||
0.1.14 / 2013-05-12
|
||||
-------------------
|
||||
|
||||
- Fixed #62, @maxtaco
|
||||
|
||||
|
||||
0.1.13 / 2013-04-08
|
||||
-------------------
|
||||
|
||||
- Added `.npmignore` to reduce package size
|
||||
|
||||
|
||||
0.1.12 / 2013-02-10
|
||||
-------------------
|
||||
|
||||
- Fixed conflictHandler (#46), @hpaulj
|
||||
|
||||
|
||||
0.1.11 / 2013-02-07
|
||||
-------------------
|
||||
|
||||
- Multiple bugfixes, @hpaulj
|
||||
- Added 70+ tests (ported from python), @hpaulj
|
||||
- Added conflictHandler, @applepicke
|
||||
- Added fromfilePrefixChar, @hpaulj
|
||||
|
||||
|
||||
0.1.10 / 2012-12-30
|
||||
-------------------
|
||||
|
||||
- Added [mutual exclusion](http://docs.python.org/dev/library/argparse.html#mutual-exclusion)
|
||||
support, thanks to @hpaulj
|
||||
- Fixed options check for `storeConst` & `appendConst` actions, thanks to @hpaulj
|
||||
|
||||
|
||||
0.1.9 / 2012-12-27
|
||||
------------------
|
||||
|
||||
- Fixed option dest interferens with other options (issue #23), thanks to @hpaulj
|
||||
- Fixed default value behavior with `*` positionals, thanks to @hpaulj
|
||||
- Improve `getDefault()` behavior, thanks to @hpaulj
|
||||
- Imrove negative argument parsing, thanks to @hpaulj
|
||||
|
||||
|
||||
0.1.8 / 2012-12-01
|
||||
------------------
|
||||
|
||||
- Fixed parser parents (issue #19), thanks to @hpaulj
|
||||
- Fixed negative argument parse (issue #20), thanks to @hpaulj
|
||||
|
||||
|
||||
0.1.7 / 2012-10-14
|
||||
------------------
|
||||
|
||||
- Fixed 'choices' argument parse (issue #16)
|
||||
- Fixed stderr output (issue #15)
|
||||
|
||||
|
||||
0.1.6 / 2012-09-09
|
||||
------------------
|
||||
|
||||
- Fixed check for conflict of options (thanks to @tomxtobin)
|
||||
|
||||
|
||||
0.1.5 / 2012-09-03
|
||||
------------------
|
||||
|
||||
- Fix parser #setDefaults method (thanks to @tomxtobin)
|
||||
|
||||
|
||||
0.1.4 / 2012-07-30
|
||||
------------------
|
||||
|
||||
- Fixed pseudo-argument support (thanks to @CGamesPlay)
|
||||
- Fixed addHelp default (should be true), if not set (thanks to @benblank)
|
||||
|
||||
|
||||
0.1.3 / 2012-06-27
|
||||
------------------
|
||||
|
||||
- Fixed formatter api name: Formatter -> HelpFormatter
|
||||
|
||||
|
||||
0.1.2 / 2012-05-29
|
||||
------------------
|
||||
|
||||
- Added basic tests
|
||||
- Removed excess whitespace in help
|
||||
- Fixed error reporting, when parcer with subcommands
|
||||
called with empty arguments
|
||||
|
||||
|
||||
0.1.1 / 2012-05-23
|
||||
------------------
|
||||
|
||||
- Fixed line wrapping in help formatter
|
||||
- Added better error reporting on invalid arguments
|
||||
|
||||
|
||||
0.1.0 / 2012-05-16
|
||||
------------------
|
||||
|
||||
- First release.
|
@ -0,0 +1,21 @@
|
||||
(The MIT License)
|
||||
|
||||
Copyright (C) 2012 by Vitaly Puzrin
|
||||
|
||||
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.
|
@ -0,0 +1,3 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = require('./lib/argparse');
|
@ -0,0 +1,146 @@
|
||||
/**
|
||||
* class Action
|
||||
*
|
||||
* Base class for all actions
|
||||
* Do not call in your code, use this class only for inherits your own action
|
||||
*
|
||||
* Information about how to convert command line strings to Javascript objects.
|
||||
* Action objects are used by an ArgumentParser to represent the information
|
||||
* needed to parse a single argument from one or more strings from the command
|
||||
* line. The keyword arguments to the Action constructor are also all attributes
|
||||
* of Action instances.
|
||||
*
|
||||
* ##### Allowed keywords:
|
||||
*
|
||||
* - `store`
|
||||
* - `storeConstant`
|
||||
* - `storeTrue`
|
||||
* - `storeFalse`
|
||||
* - `append`
|
||||
* - `appendConstant`
|
||||
* - `count`
|
||||
* - `help`
|
||||
* - `version`
|
||||
*
|
||||
* Information about action options see [[Action.new]]
|
||||
*
|
||||
* See also [original guide](http://docs.python.org/dev/library/argparse.html#action)
|
||||
*
|
||||
**/
|
||||
|
||||
'use strict';
|
||||
|
||||
|
||||
// Constants
|
||||
var c = require('./const');
|
||||
|
||||
|
||||
/**
|
||||
* new Action(options)
|
||||
*
|
||||
* Base class for all actions. Used only for inherits
|
||||
*
|
||||
*
|
||||
* ##### Options:
|
||||
*
|
||||
* - `optionStrings` A list of command-line option strings for the action.
|
||||
* - `dest` Attribute to hold the created object(s)
|
||||
* - `nargs` The number of command-line arguments that should be consumed.
|
||||
* By default, one argument will be consumed and a single value will be
|
||||
* produced.
|
||||
* - `constant` Default value for an action with no value.
|
||||
* - `defaultValue` The value to be produced if the option is not specified.
|
||||
* - `type` Cast to 'string'|'int'|'float'|'complex'|function (string). If
|
||||
* None, 'string'.
|
||||
* - `choices` The choices available.
|
||||
* - `required` True if the action must always be specified at the command
|
||||
* line.
|
||||
* - `help` The help describing the argument.
|
||||
* - `metavar` The name to be used for the option's argument with the help
|
||||
* string. If None, the 'dest' value will be used as the name.
|
||||
*
|
||||
* ##### nargs supported values:
|
||||
*
|
||||
* - `N` (an integer) consumes N arguments (and produces a list)
|
||||
* - `?` consumes zero or one arguments
|
||||
* - `*` consumes zero or more arguments (and produces a list)
|
||||
* - `+` consumes one or more arguments (and produces a list)
|
||||
*
|
||||
* Note: that the difference between the default and nargs=1 is that with the
|
||||
* default, a single value will be produced, while with nargs=1, a list
|
||||
* containing a single value will be produced.
|
||||
**/
|
||||
var Action = module.exports = function Action(options) {
|
||||
options = options || {};
|
||||
this.optionStrings = options.optionStrings || [];
|
||||
this.dest = options.dest;
|
||||
this.nargs = typeof options.nargs !== 'undefined' ? options.nargs : null;
|
||||
this.constant = typeof options.constant !== 'undefined' ? options.constant : null;
|
||||
this.defaultValue = options.defaultValue;
|
||||
this.type = typeof options.type !== 'undefined' ? options.type : null;
|
||||
this.choices = typeof options.choices !== 'undefined' ? options.choices : null;
|
||||
this.required = typeof options.required !== 'undefined' ? options.required : false;
|
||||
this.help = typeof options.help !== 'undefined' ? options.help : null;
|
||||
this.metavar = typeof options.metavar !== 'undefined' ? options.metavar : null;
|
||||
|
||||
if (!(this.optionStrings instanceof Array)) {
|
||||
throw new Error('optionStrings should be an array');
|
||||
}
|
||||
if (typeof this.required !== 'undefined' && typeof this.required !== 'boolean') {
|
||||
throw new Error('required should be a boolean');
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Action#getName -> String
|
||||
*
|
||||
* Tells action name
|
||||
**/
|
||||
Action.prototype.getName = function () {
|
||||
if (this.optionStrings.length > 0) {
|
||||
return this.optionStrings.join('/');
|
||||
} else if (this.metavar !== null && this.metavar !== c.SUPPRESS) {
|
||||
return this.metavar;
|
||||
} else if (typeof this.dest !== 'undefined' && this.dest !== c.SUPPRESS) {
|
||||
return this.dest;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Action#isOptional -> Boolean
|
||||
*
|
||||
* Return true if optional
|
||||
**/
|
||||
Action.prototype.isOptional = function () {
|
||||
return !this.isPositional();
|
||||
};
|
||||
|
||||
/**
|
||||
* Action#isPositional -> Boolean
|
||||
*
|
||||
* Return true if positional
|
||||
**/
|
||||
Action.prototype.isPositional = function () {
|
||||
return (this.optionStrings.length === 0);
|
||||
};
|
||||
|
||||
/**
|
||||
* Action#call(parser, namespace, values, optionString) -> Void
|
||||
* - parser (ArgumentParser): current parser
|
||||
* - namespace (Namespace): namespace for output data
|
||||
* - values (Array): parsed values
|
||||
* - optionString (Array): input option string(not parsed)
|
||||
*
|
||||
* Call the action. Should be implemented in inherited classes
|
||||
*
|
||||
* ##### Example
|
||||
*
|
||||
* ActionCount.prototype.call = function (parser, namespace, values, optionString) {
|
||||
* namespace.set(this.dest, (namespace[this.dest] || 0) + 1);
|
||||
* };
|
||||
*
|
||||
**/
|
||||
Action.prototype.call = function () {
|
||||
throw new Error('.call() not defined');// Not Implemented error
|
||||
};
|
@ -0,0 +1,53 @@
|
||||
/*:nodoc:*
|
||||
* class ActionAppend
|
||||
*
|
||||
* This action stores a list, and appends each argument value to the list.
|
||||
* This is useful to allow an option to be specified multiple times.
|
||||
* This class inherided from [[Action]]
|
||||
*
|
||||
**/
|
||||
|
||||
'use strict';
|
||||
|
||||
var util = require('util');
|
||||
|
||||
var Action = require('../action');
|
||||
|
||||
// Constants
|
||||
var c = require('../const');
|
||||
|
||||
/*:nodoc:*
|
||||
* new ActionAppend(options)
|
||||
* - options (object): options hash see [[Action.new]]
|
||||
*
|
||||
* Note: options.nargs should be optional for constants
|
||||
* and more then zero for other
|
||||
**/
|
||||
var ActionAppend = module.exports = function ActionAppend(options) {
|
||||
options = options || {};
|
||||
if (this.nargs <= 0) {
|
||||
throw new Error('nargs for append actions must be > 0; if arg ' +
|
||||
'strings are not supplying the value to append, ' +
|
||||
'the append const action may be more appropriate');
|
||||
}
|
||||
if (!!this.constant && this.nargs !== c.OPTIONAL) {
|
||||
throw new Error('nargs must be OPTIONAL to supply const');
|
||||
}
|
||||
Action.call(this, options);
|
||||
};
|
||||
util.inherits(ActionAppend, Action);
|
||||
|
||||
/*:nodoc:*
|
||||
* ActionAppend#call(parser, namespace, values, optionString) -> Void
|
||||
* - parser (ArgumentParser): current parser
|
||||
* - namespace (Namespace): namespace for output data
|
||||
* - values (Array): parsed values
|
||||
* - optionString (Array): input option string(not parsed)
|
||||
*
|
||||
* Call the action. Save result in namespace object
|
||||
**/
|
||||
ActionAppend.prototype.call = function (parser, namespace, values) {
|
||||
var items = (namespace[this.dest] || []).slice();
|
||||
items.push(values);
|
||||
namespace.set(this.dest, items);
|
||||
};
|
@ -0,0 +1,47 @@
|
||||
/*:nodoc:*
|
||||
* class ActionAppendConstant
|
||||
*
|
||||
* This stores a list, and appends the value specified by
|
||||
* the const keyword argument to the list.
|
||||
* (Note that the const keyword argument defaults to null.)
|
||||
* The 'appendConst' action is typically useful when multiple
|
||||
* arguments need to store constants to the same list.
|
||||
*
|
||||
* This class inherited from [[Action]]
|
||||
**/
|
||||
|
||||
'use strict';
|
||||
|
||||
var util = require('util');
|
||||
|
||||
var Action = require('../../action');
|
||||
|
||||
/*:nodoc:*
|
||||
* new ActionAppendConstant(options)
|
||||
* - options (object): options hash see [[Action.new]]
|
||||
*
|
||||
**/
|
||||
var ActionAppendConstant = module.exports = function ActionAppendConstant(options) {
|
||||
options = options || {};
|
||||
options.nargs = 0;
|
||||
if (typeof options.constant === 'undefined') {
|
||||
throw new Error('constant option is required for appendAction');
|
||||
}
|
||||
Action.call(this, options);
|
||||
};
|
||||
util.inherits(ActionAppendConstant, Action);
|
||||
|
||||
/*:nodoc:*
|
||||
* ActionAppendConstant#call(parser, namespace, values, optionString) -> Void
|
||||
* - parser (ArgumentParser): current parser
|
||||
* - namespace (Namespace): namespace for output data
|
||||
* - values (Array): parsed values
|
||||
* - optionString (Array): input option string(not parsed)
|
||||
*
|
||||
* Call the action. Save result in namespace object
|
||||
**/
|
||||
ActionAppendConstant.prototype.call = function (parser, namespace) {
|
||||
var items = [].concat(namespace[this.dest] || []);
|
||||
items.push(this.constant);
|
||||
namespace.set(this.dest, items);
|
||||
};
|
@ -0,0 +1,40 @@
|
||||
/*:nodoc:*
|
||||
* class ActionCount
|
||||
*
|
||||
* This counts the number of times a keyword argument occurs.
|
||||
* For example, this is useful for increasing verbosity levels
|
||||
*
|
||||
* This class inherided from [[Action]]
|
||||
*
|
||||
**/
|
||||
'use strict';
|
||||
|
||||
var util = require('util');
|
||||
|
||||
var Action = require('../action');
|
||||
|
||||
/*:nodoc:*
|
||||
* new ActionCount(options)
|
||||
* - options (object): options hash see [[Action.new]]
|
||||
*
|
||||
**/
|
||||
var ActionCount = module.exports = function ActionCount(options) {
|
||||
options = options || {};
|
||||
options.nargs = 0;
|
||||
|
||||
Action.call(this, options);
|
||||
};
|
||||
util.inherits(ActionCount, Action);
|
||||
|
||||
/*:nodoc:*
|
||||
* ActionCount#call(parser, namespace, values, optionString) -> Void
|
||||
* - parser (ArgumentParser): current parser
|
||||
* - namespace (Namespace): namespace for output data
|
||||
* - values (Array): parsed values
|
||||
* - optionString (Array): input option string(not parsed)
|
||||
*
|
||||
* Call the action. Save result in namespace object
|
||||
**/
|
||||
ActionCount.prototype.call = function (parser, namespace) {
|
||||
namespace.set(this.dest, (namespace[this.dest] || 0) + 1);
|
||||
};
|
@ -0,0 +1,47 @@
|
||||
/*:nodoc:*
|
||||
* class ActionHelp
|
||||
*
|
||||
* Support action for printing help
|
||||
* This class inherided from [[Action]]
|
||||
**/
|
||||
'use strict';
|
||||
|
||||
var util = require('util');
|
||||
|
||||
var Action = require('../action');
|
||||
|
||||
// Constants
|
||||
var c = require('../const');
|
||||
|
||||
/*:nodoc:*
|
||||
* new ActionHelp(options)
|
||||
* - options (object): options hash see [[Action.new]]
|
||||
*
|
||||
**/
|
||||
var ActionHelp = module.exports = function ActionHelp(options) {
|
||||
options = options || {};
|
||||
if (options.defaultValue !== null) {
|
||||
options.defaultValue = options.defaultValue;
|
||||
} else {
|
||||
options.defaultValue = c.SUPPRESS;
|
||||
}
|
||||
options.dest = (options.dest !== null ? options.dest : c.SUPPRESS);
|
||||
options.nargs = 0;
|
||||
Action.call(this, options);
|
||||
|
||||
};
|
||||
util.inherits(ActionHelp, Action);
|
||||
|
||||
/*:nodoc:*
|
||||
* ActionHelp#call(parser, namespace, values, optionString)
|
||||
* - parser (ArgumentParser): current parser
|
||||
* - namespace (Namespace): namespace for output data
|
||||
* - values (Array): parsed values
|
||||
* - optionString (Array): input option string(not parsed)
|
||||
*
|
||||
* Print help and exit
|
||||
**/
|
||||
ActionHelp.prototype.call = function (parser) {
|
||||
parser.printHelp();
|
||||
parser.exit();
|
||||
};
|
@ -0,0 +1,43 @@
|
||||
/*:nodoc:*
|
||||
* class ActionStoreConstant
|
||||
*
|
||||
* This action stores the value specified by the const keyword argument.
|
||||
* (Note that the const keyword argument defaults to the rather unhelpful null.)
|
||||
* The 'store_const' action is most commonly used with optional
|
||||
* arguments that specify some sort of flag.
|
||||
*
|
||||
* This class inherited from [[Action]]
|
||||
**/
|
||||
'use strict';
|
||||
|
||||
var util = require('util');
|
||||
|
||||
var Action = require('../../action');
|
||||
|
||||
/*:nodoc:*
|
||||
* new ActionStoreConstant(options)
|
||||
* - options (object): options hash see [[Action.new]]
|
||||
*
|
||||
**/
|
||||
var ActionStoreConstant = module.exports = function ActionStoreConstant(options) {
|
||||
options = options || {};
|
||||
options.nargs = 0;
|
||||
if (typeof options.constant === 'undefined') {
|
||||
throw new Error('constant option is required for storeAction');
|
||||
}
|
||||
Action.call(this, options);
|
||||
};
|
||||
util.inherits(ActionStoreConstant, Action);
|
||||
|
||||
/*:nodoc:*
|
||||
* ActionStoreConstant#call(parser, namespace, values, optionString) -> Void
|
||||
* - parser (ArgumentParser): current parser
|
||||
* - namespace (Namespace): namespace for output data
|
||||
* - values (Array): parsed values
|
||||
* - optionString (Array): input option string(not parsed)
|
||||
*
|
||||
* Call the action. Save result in namespace object
|
||||
**/
|
||||
ActionStoreConstant.prototype.call = function (parser, namespace) {
|
||||
namespace.set(this.dest, this.constant);
|
||||
};
|
@ -0,0 +1,27 @@
|
||||
/*:nodoc:*
|
||||
* class ActionStoreFalse
|
||||
*
|
||||
* This action store the values False respectively.
|
||||
* This is special cases of 'storeConst'
|
||||
*
|
||||
* This class inherited from [[Action]]
|
||||
**/
|
||||
|
||||
'use strict';
|
||||
|
||||
var util = require('util');
|
||||
|
||||
var ActionStoreConstant = require('./constant');
|
||||
|
||||
/*:nodoc:*
|
||||
* new ActionStoreFalse(options)
|
||||
* - options (object): hash of options see [[Action.new]]
|
||||
*
|
||||
**/
|
||||
var ActionStoreFalse = module.exports = function ActionStoreFalse(options) {
|
||||
options = options || {};
|
||||
options.constant = false;
|
||||
options.defaultValue = options.defaultValue !== null ? options.defaultValue : true;
|
||||
ActionStoreConstant.call(this, options);
|
||||
};
|
||||
util.inherits(ActionStoreFalse, ActionStoreConstant);
|
@ -0,0 +1,26 @@
|
||||
/*:nodoc:*
|
||||
* class ActionStoreTrue
|
||||
*
|
||||
* This action store the values True respectively.
|
||||
* This isspecial cases of 'storeConst'
|
||||
*
|
||||
* This class inherited from [[Action]]
|
||||
**/
|
||||
'use strict';
|
||||
|
||||
var util = require('util');
|
||||
|
||||
var ActionStoreConstant = require('./constant');
|
||||
|
||||
/*:nodoc:*
|
||||
* new ActionStoreTrue(options)
|
||||
* - options (object): options hash see [[Action.new]]
|
||||
*
|
||||
**/
|
||||
var ActionStoreTrue = module.exports = function ActionStoreTrue(options) {
|
||||
options = options || {};
|
||||
options.constant = true;
|
||||
options.defaultValue = options.defaultValue !== null ? options.defaultValue : false;
|
||||
ActionStoreConstant.call(this, options);
|
||||
};
|
||||
util.inherits(ActionStoreTrue, ActionStoreConstant);
|
@ -0,0 +1,149 @@
|
||||
/** internal
|
||||
* class ActionSubparsers
|
||||
*
|
||||
* Support the creation of such sub-commands with the addSubparsers()
|
||||
*
|
||||
* This class inherited from [[Action]]
|
||||
**/
|
||||
'use strict';
|
||||
|
||||
var util = require('util');
|
||||
var format = require('util').format;
|
||||
|
||||
|
||||
var Action = require('../action');
|
||||
|
||||
// Constants
|
||||
var c = require('../const');
|
||||
|
||||
// Errors
|
||||
var argumentErrorHelper = require('../argument/error');
|
||||
|
||||
|
||||
/*:nodoc:*
|
||||
* new ChoicesPseudoAction(name, help)
|
||||
*
|
||||
* Create pseudo action for correct help text
|
||||
*
|
||||
**/
|
||||
function ChoicesPseudoAction(name, help) {
|
||||
var options = {
|
||||
optionStrings: [],
|
||||
dest: name,
|
||||
help: help
|
||||
};
|
||||
|
||||
Action.call(this, options);
|
||||
}
|
||||
|
||||
util.inherits(ChoicesPseudoAction, Action);
|
||||
|
||||
/**
|
||||
* new ActionSubparsers(options)
|
||||
* - options (object): options hash see [[Action.new]]
|
||||
*
|
||||
**/
|
||||
function ActionSubparsers(options) {
|
||||
options = options || {};
|
||||
options.dest = options.dest || c.SUPPRESS;
|
||||
options.nargs = c.PARSER;
|
||||
|
||||
this.debug = (options.debug === true);
|
||||
|
||||
this._progPrefix = options.prog;
|
||||
this._parserClass = options.parserClass;
|
||||
this._nameParserMap = {};
|
||||
this._choicesActions = [];
|
||||
|
||||
options.choices = this._nameParserMap;
|
||||
Action.call(this, options);
|
||||
}
|
||||
|
||||
util.inherits(ActionSubparsers, Action);
|
||||
|
||||
/*:nodoc:*
|
||||
* ActionSubparsers#addParser(name, options) -> ArgumentParser
|
||||
* - name (string): sub-command name
|
||||
* - options (object): see [[ArgumentParser.new]]
|
||||
*
|
||||
* Note:
|
||||
* addParser supports an additional aliases option,
|
||||
* which allows multiple strings to refer to the same subparser.
|
||||
* This example, like svn, aliases co as a shorthand for checkout
|
||||
*
|
||||
**/
|
||||
ActionSubparsers.prototype.addParser = function (name, options) {
|
||||
var parser;
|
||||
|
||||
var self = this;
|
||||
|
||||
options = options || {};
|
||||
|
||||
options.debug = (this.debug === true);
|
||||
|
||||
// set program from the existing prefix
|
||||
if (!options.prog) {
|
||||
options.prog = this._progPrefix + ' ' + name;
|
||||
}
|
||||
|
||||
var aliases = options.aliases || [];
|
||||
|
||||
// create a pseudo-action to hold the choice help
|
||||
if (!!options.help || typeof options.help === 'string') {
|
||||
var help = options.help;
|
||||
delete options.help;
|
||||
|
||||
var choiceAction = new ChoicesPseudoAction(name, help);
|
||||
this._choicesActions.push(choiceAction);
|
||||
}
|
||||
|
||||
// create the parser and add it to the map
|
||||
parser = new this._parserClass(options);
|
||||
this._nameParserMap[name] = parser;
|
||||
|
||||
// make parser available under aliases also
|
||||
aliases.forEach(function (alias) {
|
||||
self._nameParserMap[alias] = parser;
|
||||
});
|
||||
|
||||
return parser;
|
||||
};
|
||||
|
||||
ActionSubparsers.prototype._getSubactions = function () {
|
||||
return this._choicesActions;
|
||||
};
|
||||
|
||||
/*:nodoc:*
|
||||
* ActionSubparsers#call(parser, namespace, values, optionString) -> Void
|
||||
* - parser (ArgumentParser): current parser
|
||||
* - namespace (Namespace): namespace for output data
|
||||
* - values (Array): parsed values
|
||||
* - optionString (Array): input option string(not parsed)
|
||||
*
|
||||
* Call the action. Parse input aguments
|
||||
**/
|
||||
ActionSubparsers.prototype.call = function (parser, namespace, values) {
|
||||
var parserName = values[0];
|
||||
var argStrings = values.slice(1);
|
||||
|
||||
// set the parser name if requested
|
||||
if (this.dest !== c.SUPPRESS) {
|
||||
namespace[this.dest] = parserName;
|
||||
}
|
||||
|
||||
// select the parser
|
||||
if (this._nameParserMap[parserName]) {
|
||||
parser = this._nameParserMap[parserName];
|
||||
} else {
|
||||
throw argumentErrorHelper(format(
|
||||
'Unknown parser "%s" (choices: [%s]).',
|
||||
parserName,
|
||||
Object.keys(this._nameParserMap).join(', ')
|
||||
));
|
||||
}
|
||||
|
||||
// parse all the remaining options into the namespace
|
||||
parser.parseArgs(argStrings, namespace);
|
||||
};
|
||||
|
||||
module.exports = ActionSubparsers;
|
@ -0,0 +1,47 @@
|
||||
/*:nodoc:*
|
||||
* class ActionVersion
|
||||
*
|
||||
* Support action for printing program version
|
||||
* This class inherited from [[Action]]
|
||||
**/
|
||||
'use strict';
|
||||
|
||||
var util = require('util');
|
||||
|
||||
var Action = require('../action');
|
||||
|
||||
//
|
||||
// Constants
|
||||
//
|
||||
var c = require('../const');
|
||||
|
||||
/*:nodoc:*
|
||||
* new ActionVersion(options)
|
||||
* - options (object): options hash see [[Action.new]]
|
||||
*
|
||||
**/
|
||||
var ActionVersion = module.exports = function ActionVersion(options) {
|
||||
options = options || {};
|
||||
options.defaultValue = (options.defaultValue ? options.defaultValue : c.SUPPRESS);
|
||||
options.dest = (options.dest || c.SUPPRESS);
|
||||
options.nargs = 0;
|
||||
this.version = options.version;
|
||||
Action.call(this, options);
|
||||
};
|
||||
util.inherits(ActionVersion, Action);
|
||||
|
||||
/*:nodoc:*
|
||||
* ActionVersion#call(parser, namespace, values, optionString) -> Void
|
||||
* - parser (ArgumentParser): current parser
|
||||
* - namespace (Namespace): namespace for output data
|
||||
* - values (Array): parsed values
|
||||
* - optionString (Array): input option string(not parsed)
|
||||
*
|
||||
* Print version and exit
|
||||
**/
|
||||
ActionVersion.prototype.call = function (parser) {
|
||||
var version = this.version || parser.version;
|
||||
var formatter = parser._getFormatter();
|
||||
formatter.addText(version);
|
||||
parser.exit(0, formatter.formatHelp());
|
||||
};
|
@ -0,0 +1,482 @@
|
||||
/** internal
|
||||
* class ActionContainer
|
||||
*
|
||||
* Action container. Parent for [[ArgumentParser]] and [[ArgumentGroup]]
|
||||
**/
|
||||
|
||||
'use strict';
|
||||
|
||||
var format = require('util').format;
|
||||
|
||||
// Constants
|
||||
var c = require('./const');
|
||||
|
||||
var $$ = require('./utils');
|
||||
|
||||
//Actions
|
||||
var ActionHelp = require('./action/help');
|
||||
var ActionAppend = require('./action/append');
|
||||
var ActionAppendConstant = require('./action/append/constant');
|
||||
var ActionCount = require('./action/count');
|
||||
var ActionStore = require('./action/store');
|
||||
var ActionStoreConstant = require('./action/store/constant');
|
||||
var ActionStoreTrue = require('./action/store/true');
|
||||
var ActionStoreFalse = require('./action/store/false');
|
||||
var ActionVersion = require('./action/version');
|
||||
var ActionSubparsers = require('./action/subparsers');
|
||||
|
||||
// Errors
|
||||
var argumentErrorHelper = require('./argument/error');
|
||||
|
||||
/**
|
||||
* new ActionContainer(options)
|
||||
*
|
||||
* Action container. Parent for [[ArgumentParser]] and [[ArgumentGroup]]
|
||||
*
|
||||
* ##### Options:
|
||||
*
|
||||
* - `description` -- A description of what the program does
|
||||
* - `prefixChars` -- Characters that prefix optional arguments
|
||||
* - `argumentDefault` -- The default value for all arguments
|
||||
* - `conflictHandler` -- The conflict handler to use for duplicate arguments
|
||||
**/
|
||||
var ActionContainer = module.exports = function ActionContainer(options) {
|
||||
options = options || {};
|
||||
|
||||
this.description = options.description;
|
||||
this.argumentDefault = options.argumentDefault;
|
||||
this.prefixChars = options.prefixChars || '';
|
||||
this.conflictHandler = options.conflictHandler;
|
||||
|
||||
// set up registries
|
||||
this._registries = {};
|
||||
|
||||
// register actions
|
||||
this.register('action', null, ActionStore);
|
||||
this.register('action', 'store', ActionStore);
|
||||
this.register('action', 'storeConst', ActionStoreConstant);
|
||||
this.register('action', 'storeTrue', ActionStoreTrue);
|
||||
this.register('action', 'storeFalse', ActionStoreFalse);
|
||||
this.register('action', 'append', ActionAppend);
|
||||
this.register('action', 'appendConst', ActionAppendConstant);
|
||||
this.register('action', 'count', ActionCount);
|
||||
this.register('action', 'help', ActionHelp);
|
||||
this.register('action', 'version', ActionVersion);
|
||||
this.register('action', 'parsers', ActionSubparsers);
|
||||
|
||||
// raise an exception if the conflict handler is invalid
|
||||
this._getHandler();
|
||||
|
||||
// action storage
|
||||
this._actions = [];
|
||||
this._optionStringActions = {};
|
||||
|
||||
// groups
|
||||
this._actionGroups = [];
|
||||
this._mutuallyExclusiveGroups = [];
|
||||
|
||||
// defaults storage
|
||||
this._defaults = {};
|
||||
|
||||
// determines whether an "option" looks like a negative number
|
||||
// -1, -1.5 -5e+4
|
||||
this._regexpNegativeNumber = new RegExp('^[-]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$');
|
||||
|
||||
// whether or not there are any optionals that look like negative
|
||||
// numbers -- uses a list so it can be shared and edited
|
||||
this._hasNegativeNumberOptionals = [];
|
||||
};
|
||||
|
||||
// Groups must be required, then ActionContainer already defined
|
||||
var ArgumentGroup = require('./argument/group');
|
||||
var MutuallyExclusiveGroup = require('./argument/exclusive');
|
||||
|
||||
//
|
||||
// Registration methods
|
||||
//
|
||||
|
||||
/**
|
||||
* ActionContainer#register(registryName, value, object) -> Void
|
||||
* - registryName (String) : object type action|type
|
||||
* - value (string) : keyword
|
||||
* - object (Object|Function) : handler
|
||||
*
|
||||
* Register handlers
|
||||
**/
|
||||
ActionContainer.prototype.register = function (registryName, value, object) {
|
||||
this._registries[registryName] = this._registries[registryName] || {};
|
||||
this._registries[registryName][value] = object;
|
||||
};
|
||||
|
||||
ActionContainer.prototype._registryGet = function (registryName, value, defaultValue) {
|
||||
if (arguments.length < 3) {
|
||||
defaultValue = null;
|
||||
}
|
||||
return this._registries[registryName][value] || defaultValue;
|
||||
};
|
||||
|
||||
//
|
||||
// Namespace default accessor methods
|
||||
//
|
||||
|
||||
/**
|
||||
* ActionContainer#setDefaults(options) -> Void
|
||||
* - options (object):hash of options see [[Action.new]]
|
||||
*
|
||||
* Set defaults
|
||||
**/
|
||||
ActionContainer.prototype.setDefaults = function (options) {
|
||||
options = options || {};
|
||||
for (var property in options) {
|
||||
if ($$.has(options, property)) {
|
||||
this._defaults[property] = options[property];
|
||||
}
|
||||
}
|
||||
|
||||
// if these defaults match any existing arguments, replace the previous
|
||||
// default on the object with the new one
|
||||
this._actions.forEach(function (action) {
|
||||
if ($$.has(options, action.dest)) {
|
||||
action.defaultValue = options[action.dest];
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* ActionContainer#getDefault(dest) -> Mixed
|
||||
* - dest (string): action destination
|
||||
*
|
||||
* Return action default value
|
||||
**/
|
||||
ActionContainer.prototype.getDefault = function (dest) {
|
||||
var result = $$.has(this._defaults, dest) ? this._defaults[dest] : null;
|
||||
|
||||
this._actions.forEach(function (action) {
|
||||
if (action.dest === dest && $$.has(action, 'defaultValue')) {
|
||||
result = action.defaultValue;
|
||||
}
|
||||
});
|
||||
|
||||
return result;
|
||||
};
|
||||
//
|
||||
// Adding argument actions
|
||||
//
|
||||
|
||||
/**
|
||||
* ActionContainer#addArgument(args, options) -> Object
|
||||
* - args (String|Array): argument key, or array of argument keys
|
||||
* - options (Object): action objects see [[Action.new]]
|
||||
*
|
||||
* #### Examples
|
||||
* - addArgument([ '-f', '--foo' ], { action: 'store', defaultValue: 1, ... })
|
||||
* - addArgument([ 'bar' ], { action: 'store', nargs: 1, ... })
|
||||
* - addArgument('--baz', { action: 'store', nargs: 1, ... })
|
||||
**/
|
||||
ActionContainer.prototype.addArgument = function (args, options) {
|
||||
args = args;
|
||||
options = options || {};
|
||||
|
||||
if (typeof args === 'string') {
|
||||
args = [ args ];
|
||||
}
|
||||
if (!Array.isArray(args)) {
|
||||
throw new TypeError('addArgument first argument should be a string or an array');
|
||||
}
|
||||
if (typeof options !== 'object' || Array.isArray(options)) {
|
||||
throw new TypeError('addArgument second argument should be a hash');
|
||||
}
|
||||
|
||||
// if no positional args are supplied or only one is supplied and
|
||||
// it doesn't look like an option string, parse a positional argument
|
||||
if (!args || args.length === 1 && this.prefixChars.indexOf(args[0][0]) < 0) {
|
||||
if (args && !!options.dest) {
|
||||
throw new Error('dest supplied twice for positional argument');
|
||||
}
|
||||
options = this._getPositional(args, options);
|
||||
|
||||
// otherwise, we're adding an optional argument
|
||||
} else {
|
||||
options = this._getOptional(args, options);
|
||||
}
|
||||
|
||||
// if no default was supplied, use the parser-level default
|
||||
if (typeof options.defaultValue === 'undefined') {
|
||||
var dest = options.dest;
|
||||
if ($$.has(this._defaults, dest)) {
|
||||
options.defaultValue = this._defaults[dest];
|
||||
} else if (typeof this.argumentDefault !== 'undefined') {
|
||||
options.defaultValue = this.argumentDefault;
|
||||
}
|
||||
}
|
||||
|
||||
// create the action object, and add it to the parser
|
||||
var ActionClass = this._popActionClass(options);
|
||||
if (typeof ActionClass !== 'function') {
|
||||
throw new Error(format('Unknown action "%s".', ActionClass));
|
||||
}
|
||||
var action = new ActionClass(options);
|
||||
|
||||
// throw an error if the action type is not callable
|
||||
var typeFunction = this._registryGet('type', action.type, action.type);
|
||||
if (typeof typeFunction !== 'function') {
|
||||
throw new Error(format('"%s" is not callable', typeFunction));
|
||||
}
|
||||
|
||||
return this._addAction(action);
|
||||
};
|
||||
|
||||
/**
|
||||
* ActionContainer#addArgumentGroup(options) -> ArgumentGroup
|
||||
* - options (Object): hash of options see [[ArgumentGroup.new]]
|
||||
*
|
||||
* Create new arguments groups
|
||||
**/
|
||||
ActionContainer.prototype.addArgumentGroup = function (options) {
|
||||
var group = new ArgumentGroup(this, options);
|
||||
this._actionGroups.push(group);
|
||||
return group;
|
||||
};
|
||||
|
||||
/**
|
||||
* ActionContainer#addMutuallyExclusiveGroup(options) -> ArgumentGroup
|
||||
* - options (Object): {required: false}
|
||||
*
|
||||
* Create new mutual exclusive groups
|
||||
**/
|
||||
ActionContainer.prototype.addMutuallyExclusiveGroup = function (options) {
|
||||
var group = new MutuallyExclusiveGroup(this, options);
|
||||
this._mutuallyExclusiveGroups.push(group);
|
||||
return group;
|
||||
};
|
||||
|
||||
ActionContainer.prototype._addAction = function (action) {
|
||||
var self = this;
|
||||
|
||||
// resolve any conflicts
|
||||
this._checkConflict(action);
|
||||
|
||||
// add to actions list
|
||||
this._actions.push(action);
|
||||
action.container = this;
|
||||
|
||||
// index the action by any option strings it has
|
||||
action.optionStrings.forEach(function (optionString) {
|
||||
self._optionStringActions[optionString] = action;
|
||||
});
|
||||
|
||||
// set the flag if any option strings look like negative numbers
|
||||
action.optionStrings.forEach(function (optionString) {
|
||||
if (optionString.match(self._regexpNegativeNumber)) {
|
||||
if (!self._hasNegativeNumberOptionals.some(Boolean)) {
|
||||
self._hasNegativeNumberOptionals.push(true);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// return the created action
|
||||
return action;
|
||||
};
|
||||
|
||||
ActionContainer.prototype._removeAction = function (action) {
|
||||
var actionIndex = this._actions.indexOf(action);
|
||||
if (actionIndex >= 0) {
|
||||
this._actions.splice(actionIndex, 1);
|
||||
}
|
||||
};
|
||||
|
||||
ActionContainer.prototype._addContainerActions = function (container) {
|
||||
// collect groups by titles
|
||||
var titleGroupMap = {};
|
||||
this._actionGroups.forEach(function (group) {
|
||||
if (titleGroupMap[group.title]) {
|
||||
throw new Error(format('Cannot merge actions - two groups are named "%s".', group.title));
|
||||
}
|
||||
titleGroupMap[group.title] = group;
|
||||
});
|
||||
|
||||
// map each action to its group
|
||||
var groupMap = {};
|
||||
function actionHash(action) {
|
||||
// unique (hopefully?) string suitable as dictionary key
|
||||
return action.getName();
|
||||
}
|
||||
container._actionGroups.forEach(function (group) {
|
||||
// if a group with the title exists, use that, otherwise
|
||||
// create a new group matching the container's group
|
||||
if (!titleGroupMap[group.title]) {
|
||||
titleGroupMap[group.title] = this.addArgumentGroup({
|
||||
title: group.title,
|
||||
description: group.description
|
||||
});
|
||||
}
|
||||
|
||||
// map the actions to their new group
|
||||
group._groupActions.forEach(function (action) {
|
||||
groupMap[actionHash(action)] = titleGroupMap[group.title];
|
||||
});
|
||||
}, this);
|
||||
|
||||
// add container's mutually exclusive groups
|
||||
// NOTE: if add_mutually_exclusive_group ever gains title= and
|
||||
// description= then this code will need to be expanded as above
|
||||
var mutexGroup;
|
||||
container._mutuallyExclusiveGroups.forEach(function (group) {
|
||||
mutexGroup = this.addMutuallyExclusiveGroup({
|
||||
required: group.required
|
||||
});
|
||||
// map the actions to their new mutex group
|
||||
group._groupActions.forEach(function (action) {
|
||||
groupMap[actionHash(action)] = mutexGroup;
|
||||
});
|
||||
}, this); // forEach takes a 'this' argument
|
||||
|
||||
// add all actions to this container or their group
|
||||
container._actions.forEach(function (action) {
|
||||
var key = actionHash(action);
|
||||
if (groupMap[key]) {
|
||||
groupMap[key]._addAction(action);
|
||||
} else {
|
||||
this._addAction(action);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
ActionContainer.prototype._getPositional = function (dest, options) {
|
||||
if (Array.isArray(dest)) {
|
||||
dest = dest[0];
|
||||
}
|
||||
// make sure required is not specified
|
||||
if (options.required) {
|
||||
throw new Error('"required" is an invalid argument for positionals.');
|
||||
}
|
||||
|
||||
// mark positional arguments as required if at least one is
|
||||
// always required
|
||||
if (options.nargs !== c.OPTIONAL && options.nargs !== c.ZERO_OR_MORE) {
|
||||
options.required = true;
|
||||
}
|
||||
if (options.nargs === c.ZERO_OR_MORE && typeof options.defaultValue === 'undefined') {
|
||||
options.required = true;
|
||||
}
|
||||
|
||||
// return the keyword arguments with no option strings
|
||||
options.dest = dest;
|
||||
options.optionStrings = [];
|
||||
return options;
|
||||
};
|
||||
|
||||
ActionContainer.prototype._getOptional = function (args, options) {
|
||||
var prefixChars = this.prefixChars;
|
||||
var optionStrings = [];
|
||||
var optionStringsLong = [];
|
||||
|
||||
// determine short and long option strings
|
||||
args.forEach(function (optionString) {
|
||||
// error on strings that don't start with an appropriate prefix
|
||||
if (prefixChars.indexOf(optionString[0]) < 0) {
|
||||
throw new Error(format('Invalid option string "%s": must start with a "%s".',
|
||||
optionString,
|
||||
prefixChars
|
||||
));
|
||||
}
|
||||
|
||||
// strings starting with two prefix characters are long options
|
||||
optionStrings.push(optionString);
|
||||
if (optionString.length > 1 && prefixChars.indexOf(optionString[1]) >= 0) {
|
||||
optionStringsLong.push(optionString);
|
||||
}
|
||||
});
|
||||
|
||||
// infer dest, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
|
||||
var dest = options.dest || null;
|
||||
delete options.dest;
|
||||
|
||||
if (!dest) {
|
||||
var optionStringDest = optionStringsLong.length ? optionStringsLong[0] : optionStrings[0];
|
||||
dest = $$.trimChars(optionStringDest, this.prefixChars);
|
||||
|
||||
if (dest.length === 0) {
|
||||
throw new Error(
|
||||
format('dest= is required for options like "%s"', optionStrings.join(', '))
|
||||
);
|
||||
}
|
||||
dest = dest.replace(/-/g, '_');
|
||||
}
|
||||
|
||||
// return the updated keyword arguments
|
||||
options.dest = dest;
|
||||
options.optionStrings = optionStrings;
|
||||
|
||||
return options;
|
||||
};
|
||||
|
||||
ActionContainer.prototype._popActionClass = function (options, defaultValue) {
|
||||
defaultValue = defaultValue || null;
|
||||
|
||||
var action = (options.action || defaultValue);
|
||||
delete options.action;
|
||||
|
||||
var actionClass = this._registryGet('action', action, action);
|
||||
return actionClass;
|
||||
};
|
||||
|
||||
ActionContainer.prototype._getHandler = function () {
|
||||
var handlerString = this.conflictHandler;
|
||||
var handlerFuncName = '_handleConflict' + $$.capitalize(handlerString);
|
||||
var func = this[handlerFuncName];
|
||||
if (typeof func === 'undefined') {
|
||||
var msg = 'invalid conflict resolution value: ' + handlerString;
|
||||
throw new Error(msg);
|
||||
} else {
|
||||
return func;
|
||||
}
|
||||
};
|
||||
|
||||
ActionContainer.prototype._checkConflict = function (action) {
|
||||
var optionStringActions = this._optionStringActions;
|
||||
var conflictOptionals = [];
|
||||
|
||||
// find all options that conflict with this option
|
||||
// collect pairs, the string, and an existing action that it conflicts with
|
||||
action.optionStrings.forEach(function (optionString) {
|
||||
var conflOptional = optionStringActions[optionString];
|
||||
if (typeof conflOptional !== 'undefined') {
|
||||
conflictOptionals.push([ optionString, conflOptional ]);
|
||||
}
|
||||
});
|
||||
|
||||
if (conflictOptionals.length > 0) {
|
||||
var conflictHandler = this._getHandler();
|
||||
conflictHandler.call(this, action, conflictOptionals);
|
||||
}
|
||||
};
|
||||
|
||||
ActionContainer.prototype._handleConflictError = function (action, conflOptionals) {
|
||||
var conflicts = conflOptionals.map(function (pair) { return pair[0]; });
|
||||
conflicts = conflicts.join(', ');
|
||||
throw argumentErrorHelper(
|
||||
action,
|
||||
format('Conflicting option string(s): %s', conflicts)
|
||||
);
|
||||
};
|
||||
|
||||
ActionContainer.prototype._handleConflictResolve = function (action, conflOptionals) {
|
||||
// remove all conflicting options
|
||||
var self = this;
|
||||
conflOptionals.forEach(function (pair) {
|
||||
var optionString = pair[0];
|
||||
var conflictingAction = pair[1];
|
||||
// remove the conflicting option string
|
||||
var i = conflictingAction.optionStrings.indexOf(optionString);
|
||||
if (i >= 0) {
|
||||
conflictingAction.optionStrings.splice(i, 1);
|
||||
}
|
||||
delete self._optionStringActions[optionString];
|
||||
// if the option now has no option string, remove it from the
|
||||
// container holding it
|
||||
if (conflictingAction.optionStrings.length === 0) {
|
||||
conflictingAction.container._removeAction(conflictingAction);
|
||||
}
|
||||
});
|
||||
};
|
@ -0,0 +1,14 @@
|
||||
'use strict';
|
||||
|
||||
module.exports.ArgumentParser = require('./argument_parser.js');
|
||||
module.exports.Namespace = require('./namespace');
|
||||
module.exports.Action = require('./action');
|
||||
module.exports.HelpFormatter = require('./help/formatter.js');
|
||||
module.exports.Const = require('./const.js');
|
||||
|
||||
module.exports.ArgumentDefaultsHelpFormatter =
|
||||
require('./help/added_formatters.js').ArgumentDefaultsHelpFormatter;
|
||||
module.exports.RawDescriptionHelpFormatter =
|
||||
require('./help/added_formatters.js').RawDescriptionHelpFormatter;
|
||||
module.exports.RawTextHelpFormatter =
|
||||
require('./help/added_formatters.js').RawTextHelpFormatter;
|
@ -0,0 +1,50 @@
|
||||
'use strict';
|
||||
|
||||
|
||||
var format = require('util').format;
|
||||
|
||||
|
||||
var ERR_CODE = 'ARGError';
|
||||
|
||||
/*:nodoc:*
|
||||
* argumentError(argument, message) -> TypeError
|
||||
* - argument (Object): action with broken argument
|
||||
* - message (String): error message
|
||||
*
|
||||
* Error format helper. An error from creating or using an argument
|
||||
* (optional or positional). The string value of this exception
|
||||
* is the message, augmented with information
|
||||
* about the argument that caused it.
|
||||
*
|
||||
* #####Example
|
||||
*
|
||||
* var argumentErrorHelper = require('./argument/error');
|
||||
* if (conflictOptionals.length > 0) {
|
||||
* throw argumentErrorHelper(
|
||||
* action,
|
||||
* format('Conflicting option string(s): %s', conflictOptionals.join(', '))
|
||||
* );
|
||||
* }
|
||||
*
|
||||
**/
|
||||
module.exports = function (argument, message) {
|
||||
var argumentName = null;
|
||||
var errMessage;
|
||||
var err;
|
||||
|
||||
if (argument.getName) {
|
||||
argumentName = argument.getName();
|
||||
} else {
|
||||
argumentName = '' + argument;
|
||||
}
|
||||
|
||||
if (!argumentName) {
|
||||
errMessage = message;
|
||||
} else {
|
||||
errMessage = format('argument "%s": %s', argumentName, message);
|
||||
}
|
||||
|
||||
err = new TypeError(errMessage);
|
||||
err.code = ERR_CODE;
|
||||
return err;
|
||||
};
|
@ -0,0 +1,54 @@
|
||||
/** internal
|
||||
* class MutuallyExclusiveGroup
|
||||
*
|
||||
* Group arguments.
|
||||
* By default, ArgumentParser groups command-line arguments
|
||||
* into “positional arguments” and “optional arguments”
|
||||
* when displaying help messages. When there is a better
|
||||
* conceptual grouping of arguments than this default one,
|
||||
* appropriate groups can be created using the addArgumentGroup() method
|
||||
*
|
||||
* This class inherited from [[ArgumentContainer]]
|
||||
**/
|
||||
'use strict';
|
||||
|
||||
var util = require('util');
|
||||
|
||||
var ArgumentGroup = require('./group');
|
||||
|
||||
/**
|
||||
* new MutuallyExclusiveGroup(container, options)
|
||||
* - container (object): main container
|
||||
* - options (object): options.required -> true/false
|
||||
*
|
||||
* `required` could be an argument itself, but making it a property of
|
||||
* the options argument is more consistent with the JS adaptation of the Python)
|
||||
**/
|
||||
var MutuallyExclusiveGroup = module.exports = function MutuallyExclusiveGroup(container, options) {
|
||||
var required;
|
||||
options = options || {};
|
||||
required = options.required || false;
|
||||
ArgumentGroup.call(this, container);
|
||||
this.required = required;
|
||||
|
||||
};
|
||||
util.inherits(MutuallyExclusiveGroup, ArgumentGroup);
|
||||
|
||||
|
||||
MutuallyExclusiveGroup.prototype._addAction = function (action) {
|
||||
var msg;
|
||||
if (action.required) {
|
||||
msg = 'mutually exclusive arguments must be optional';
|
||||
throw new Error(msg);
|
||||
}
|
||||
action = this._container._addAction(action);
|
||||
this._groupActions.push(action);
|
||||
return action;
|
||||
};
|
||||
|
||||
|
||||
MutuallyExclusiveGroup.prototype._removeAction = function (action) {
|
||||
this._container._removeAction(action);
|
||||
this._groupActions.remove(action);
|
||||
};
|
||||
|
@ -0,0 +1,75 @@
|
||||
/** internal
|
||||
* class ArgumentGroup
|
||||
*
|
||||
* Group arguments.
|
||||
* By default, ArgumentParser groups command-line arguments
|
||||
* into “positional arguments” and “optional arguments”
|
||||
* when displaying help messages. When there is a better
|
||||
* conceptual grouping of arguments than this default one,
|
||||
* appropriate groups can be created using the addArgumentGroup() method
|
||||
*
|
||||
* This class inherited from [[ArgumentContainer]]
|
||||
**/
|
||||
'use strict';
|
||||
|
||||
var util = require('util');
|
||||
|
||||
var ActionContainer = require('../action_container');
|
||||
|
||||
|
||||
/**
|
||||
* new ArgumentGroup(container, options)
|
||||
* - container (object): main container
|
||||
* - options (object): hash of group options
|
||||
*
|
||||
* #### options
|
||||
* - **prefixChars** group name prefix
|
||||
* - **argumentDefault** default argument value
|
||||
* - **title** group title
|
||||
* - **description** group description
|
||||
*
|
||||
**/
|
||||
var ArgumentGroup = module.exports = function ArgumentGroup(container, options) {
|
||||
|
||||
options = options || {};
|
||||
|
||||
// add any missing keyword arguments by checking the container
|
||||
options.conflictHandler = (options.conflictHandler || container.conflictHandler);
|
||||
options.prefixChars = (options.prefixChars || container.prefixChars);
|
||||
options.argumentDefault = (options.argumentDefault || container.argumentDefault);
|
||||
|
||||
ActionContainer.call(this, options);
|
||||
|
||||
// group attributes
|
||||
this.title = options.title;
|
||||
this._groupActions = [];
|
||||
|
||||
// share most attributes with the container
|
||||
this._container = container;
|
||||
this._registries = container._registries;
|
||||
this._actions = container._actions;
|
||||
this._optionStringActions = container._optionStringActions;
|
||||
this._defaults = container._defaults;
|
||||
this._hasNegativeNumberOptionals = container._hasNegativeNumberOptionals;
|
||||
this._mutuallyExclusiveGroups = container._mutuallyExclusiveGroups;
|
||||
};
|
||||
util.inherits(ArgumentGroup, ActionContainer);
|
||||
|
||||
|
||||
ArgumentGroup.prototype._addAction = function (action) {
|
||||
// Parent add action
|
||||
action = ActionContainer.prototype._addAction.call(this, action);
|
||||
this._groupActions.push(action);
|
||||
return action;
|
||||
};
|
||||
|
||||
|
||||
ArgumentGroup.prototype._removeAction = function (action) {
|
||||
// Parent remove action
|
||||
ActionContainer.prototype._removeAction.call(this, action);
|
||||
var actionIndex = this._groupActions.indexOf(action);
|
||||
if (actionIndex >= 0) {
|
||||
this._groupActions.splice(actionIndex, 1);
|
||||
}
|
||||
};
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,21 @@
|
||||
//
|
||||
// Constants
|
||||
//
|
||||
|
||||
'use strict';
|
||||
|
||||
module.exports.EOL = '\n';
|
||||
|
||||
module.exports.SUPPRESS = '==SUPPRESS==';
|
||||
|
||||
module.exports.OPTIONAL = '?';
|
||||
|
||||
module.exports.ZERO_OR_MORE = '*';
|
||||
|
||||
module.exports.ONE_OR_MORE = '+';
|
||||
|
||||
module.exports.PARSER = 'A...';
|
||||
|
||||
module.exports.REMAINDER = '...';
|
||||
|
||||
module.exports._UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args';
|
@ -0,0 +1,87 @@
|
||||
'use strict';
|
||||
|
||||
var util = require('util');
|
||||
|
||||
// Constants
|
||||
var c = require('../const');
|
||||
|
||||
var $$ = require('../utils');
|
||||
var HelpFormatter = require('./formatter.js');
|
||||
|
||||
/**
|
||||
* new RawDescriptionHelpFormatter(options)
|
||||
* new ArgumentParser({formatterClass: argparse.RawDescriptionHelpFormatter, ...})
|
||||
*
|
||||
* Help message formatter which adds default values to argument help.
|
||||
*
|
||||
* Only the name of this class is considered a public API. All the methods
|
||||
* provided by the class are considered an implementation detail.
|
||||
**/
|
||||
|
||||
function ArgumentDefaultsHelpFormatter(options) {
|
||||
HelpFormatter.call(this, options);
|
||||
}
|
||||
|
||||
util.inherits(ArgumentDefaultsHelpFormatter, HelpFormatter);
|
||||
|
||||
ArgumentDefaultsHelpFormatter.prototype._getHelpString = function (action) {
|
||||
var help = action.help;
|
||||
if (action.help.indexOf('%(defaultValue)s') === -1) {
|
||||
if (action.defaultValue !== c.SUPPRESS) {
|
||||
var defaulting_nargs = [ c.OPTIONAL, c.ZERO_OR_MORE ];
|
||||
if (action.isOptional() || (defaulting_nargs.indexOf(action.nargs) >= 0)) {
|
||||
help += ' (default: %(defaultValue)s)';
|
||||
}
|
||||
}
|
||||
}
|
||||
return help;
|
||||
};
|
||||
|
||||
module.exports.ArgumentDefaultsHelpFormatter = ArgumentDefaultsHelpFormatter;
|
||||
|
||||
/**
|
||||
* new RawDescriptionHelpFormatter(options)
|
||||
* new ArgumentParser({formatterClass: argparse.RawDescriptionHelpFormatter, ...})
|
||||
*
|
||||
* Help message formatter which retains any formatting in descriptions.
|
||||
*
|
||||
* Only the name of this class is considered a public API. All the methods
|
||||
* provided by the class are considered an implementation detail.
|
||||
**/
|
||||
|
||||
function RawDescriptionHelpFormatter(options) {
|
||||
HelpFormatter.call(this, options);
|
||||
}
|
||||
|
||||
util.inherits(RawDescriptionHelpFormatter, HelpFormatter);
|
||||
|
||||
RawDescriptionHelpFormatter.prototype._fillText = function (text, width, indent) {
|
||||
var lines = text.split('\n');
|
||||
lines = lines.map(function (line) {
|
||||
return $$.trimEnd(indent + line);
|
||||
});
|
||||
return lines.join('\n');
|
||||
};
|
||||
module.exports.RawDescriptionHelpFormatter = RawDescriptionHelpFormatter;
|
||||
|
||||
/**
|
||||
* new RawTextHelpFormatter(options)
|
||||
* new ArgumentParser({formatterClass: argparse.RawTextHelpFormatter, ...})
|
||||
*
|
||||
* Help message formatter which retains formatting of all help text.
|
||||
*
|
||||
* Only the name of this class is considered a public API. All the methods
|
||||
* provided by the class are considered an implementation detail.
|
||||
**/
|
||||
|
||||
function RawTextHelpFormatter(options) {
|
||||
RawDescriptionHelpFormatter.call(this, options);
|
||||
}
|
||||
|
||||
util.inherits(RawTextHelpFormatter, RawDescriptionHelpFormatter);
|
||||
|
||||
RawTextHelpFormatter.prototype._splitLines = function (text) {
|
||||
return text.split('\n');
|
||||
};
|
||||
|
||||
module.exports.RawTextHelpFormatter = RawTextHelpFormatter;
|
@ -0,0 +1,795 @@
|
||||
/**
|
||||
* class HelpFormatter
|
||||
*
|
||||
* Formatter for generating usage messages and argument help strings. Only the
|
||||
* name of this class is considered a public API. All the methods provided by
|
||||
* the class are considered an implementation detail.
|
||||
*
|
||||
* Do not call in your code, use this class only for inherits your own forvatter
|
||||
*
|
||||
* ToDo add [additonal formatters][1]
|
||||
*
|
||||
* [1]:http://docs.python.org/dev/library/argparse.html#formatter-class
|
||||
**/
|
||||
'use strict';
|
||||
|
||||
var sprintf = require('sprintf-js').sprintf;
|
||||
|
||||
// Constants
|
||||
var c = require('../const');
|
||||
|
||||
var $$ = require('../utils');
|
||||
|
||||
|
||||
/*:nodoc:* internal
|
||||
* new Support(parent, heding)
|
||||
* - parent (object): parent section
|
||||
* - heading (string): header string
|
||||
*
|
||||
**/
|
||||
function Section(parent, heading) {
|
||||
this._parent = parent;
|
||||
this._heading = heading;
|
||||
this._items = [];
|
||||
}
|
||||
|
||||
/*:nodoc:* internal
|
||||
* Section#addItem(callback) -> Void
|
||||
* - callback (array): tuple with function and args
|
||||
*
|
||||
* Add function for single element
|
||||
**/
|
||||
Section.prototype.addItem = function (callback) {
|
||||
this._items.push(callback);
|
||||
};
|
||||
|
||||
/*:nodoc:* internal
|
||||
* Section#formatHelp(formatter) -> string
|
||||
* - formatter (HelpFormatter): current formatter
|
||||
*
|
||||
* Form help section string
|
||||
*
|
||||
**/
|
||||
Section.prototype.formatHelp = function (formatter) {
|
||||
var itemHelp, heading;
|
||||
|
||||
// format the indented section
|
||||
if (this._parent) {
|
||||
formatter._indent();
|
||||
}
|
||||
|
||||
itemHelp = this._items.map(function (item) {
|
||||
var obj, func, args;
|
||||
|
||||
obj = formatter;
|
||||
func = item[0];
|
||||
args = item[1];
|
||||
return func.apply(obj, args);
|
||||
});
|
||||
itemHelp = formatter._joinParts(itemHelp);
|
||||
|
||||
if (this._parent) {
|
||||
formatter._dedent();
|
||||
}
|
||||
|
||||
// return nothing if the section was empty
|
||||
if (!itemHelp) {
|
||||
return '';
|
||||
}
|
||||
|
||||
// add the heading if the section was non-empty
|
||||
heading = '';
|
||||
if (this._heading && this._heading !== c.SUPPRESS) {
|
||||
var currentIndent = formatter.currentIndent;
|
||||
heading = $$.repeat(' ', currentIndent) + this._heading + ':' + c.EOL;
|
||||
}
|
||||
|
||||
// join the section-initialize newline, the heading and the help
|
||||
return formatter._joinParts([ c.EOL, heading, itemHelp, c.EOL ]);
|
||||
};
|
||||
|
||||
/**
|
||||
* new HelpFormatter(options)
|
||||
*
|
||||
* #### Options:
|
||||
* - `prog`: program name
|
||||
* - `indentIncriment`: indent step, default value 2
|
||||
* - `maxHelpPosition`: max help position, default value = 24
|
||||
* - `width`: line width
|
||||
*
|
||||
**/
|
||||
var HelpFormatter = module.exports = function HelpFormatter(options) {
|
||||
options = options || {};
|
||||
|
||||
this._prog = options.prog;
|
||||
|
||||
this._maxHelpPosition = options.maxHelpPosition || 24;
|
||||
this._width = (options.width || ((process.env.COLUMNS || 80) - 2));
|
||||
|
||||
this._currentIndent = 0;
|
||||
this._indentIncriment = options.indentIncriment || 2;
|
||||
this._level = 0;
|
||||
this._actionMaxLength = 0;
|
||||
|
||||
this._rootSection = new Section(null);
|
||||
this._currentSection = this._rootSection;
|
||||
|
||||
this._whitespaceMatcher = new RegExp('\\s+', 'g');
|
||||
this._longBreakMatcher = new RegExp(c.EOL + c.EOL + c.EOL + '+', 'g');
|
||||
};
|
||||
|
||||
HelpFormatter.prototype._indent = function () {
|
||||
this._currentIndent += this._indentIncriment;
|
||||
this._level += 1;
|
||||
};
|
||||
|
||||
HelpFormatter.prototype._dedent = function () {
|
||||
this._currentIndent -= this._indentIncriment;
|
||||
this._level -= 1;
|
||||
if (this._currentIndent < 0) {
|
||||
throw new Error('Indent decreased below 0.');
|
||||
}
|
||||
};
|
||||
|
||||
HelpFormatter.prototype._addItem = function (func, args) {
|
||||
this._currentSection.addItem([ func, args ]);
|
||||
};
|
||||
|
||||
//
|
||||
// Message building methods
|
||||
//
|
||||
|
||||
/**
|
||||
* HelpFormatter#startSection(heading) -> Void
|
||||
* - heading (string): header string
|
||||
*
|
||||
* Start new help section
|
||||
*
|
||||
* See alse [code example][1]
|
||||
*
|
||||
* ##### Example
|
||||
*
|
||||
* formatter.startSection(actionGroup.title);
|
||||
* formatter.addText(actionGroup.description);
|
||||
* formatter.addArguments(actionGroup._groupActions);
|
||||
* formatter.endSection();
|
||||
*
|
||||
**/
|
||||
HelpFormatter.prototype.startSection = function (heading) {
|
||||
this._indent();
|
||||
var section = new Section(this._currentSection, heading);
|
||||
var func = section.formatHelp.bind(section);
|
||||
this._addItem(func, [ this ]);
|
||||
this._currentSection = section;
|
||||
};
|
||||
|
||||
/**
|
||||
* HelpFormatter#endSection -> Void
|
||||
*
|
||||
* End help section
|
||||
*
|
||||
* ##### Example
|
||||
*
|
||||
* formatter.startSection(actionGroup.title);
|
||||
* formatter.addText(actionGroup.description);
|
||||
* formatter.addArguments(actionGroup._groupActions);
|
||||
* formatter.endSection();
|
||||
**/
|
||||
HelpFormatter.prototype.endSection = function () {
|
||||
this._currentSection = this._currentSection._parent;
|
||||
this._dedent();
|
||||
};
|
||||
|
||||
/**
|
||||
* HelpFormatter#addText(text) -> Void
|
||||
* - text (string): plain text
|
||||
*
|
||||
* Add plain text into current section
|
||||
*
|
||||
* ##### Example
|
||||
*
|
||||
* formatter.startSection(actionGroup.title);
|
||||
* formatter.addText(actionGroup.description);
|
||||
* formatter.addArguments(actionGroup._groupActions);
|
||||
* formatter.endSection();
|
||||
*
|
||||
**/
|
||||
HelpFormatter.prototype.addText = function (text) {
|
||||
if (text && text !== c.SUPPRESS) {
|
||||
this._addItem(this._formatText, [ text ]);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* HelpFormatter#addUsage(usage, actions, groups, prefix) -> Void
|
||||
* - usage (string): usage text
|
||||
* - actions (array): actions list
|
||||
* - groups (array): groups list
|
||||
* - prefix (string): usage prefix
|
||||
*
|
||||
* Add usage data into current section
|
||||
*
|
||||
* ##### Example
|
||||
*
|
||||
* formatter.addUsage(this.usage, this._actions, []);
|
||||
* return formatter.formatHelp();
|
||||
*
|
||||
**/
|
||||
HelpFormatter.prototype.addUsage = function (usage, actions, groups, prefix) {
|
||||
if (usage !== c.SUPPRESS) {
|
||||
this._addItem(this._formatUsage, [ usage, actions, groups, prefix ]);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* HelpFormatter#addArgument(action) -> Void
|
||||
* - action (object): action
|
||||
*
|
||||
* Add argument into current section
|
||||
*
|
||||
* Single variant of [[HelpFormatter#addArguments]]
|
||||
**/
|
||||
HelpFormatter.prototype.addArgument = function (action) {
|
||||
if (action.help !== c.SUPPRESS) {
|
||||
var self = this;
|
||||
|
||||
// find all invocations
|
||||
var invocations = [ this._formatActionInvocation(action) ];
|
||||
var invocationLength = invocations[0].length;
|
||||
|
||||
var actionLength;
|
||||
|
||||
if (action._getSubactions) {
|
||||
this._indent();
|
||||
action._getSubactions().forEach(function (subaction) {
|
||||
|
||||
var invocationNew = self._formatActionInvocation(subaction);
|
||||
invocations.push(invocationNew);
|
||||
invocationLength = Math.max(invocationLength, invocationNew.length);
|
||||
|
||||
});
|
||||
this._dedent();
|
||||
}
|
||||
|
||||
// update the maximum item length
|
||||
actionLength = invocationLength + this._currentIndent;
|
||||
this._actionMaxLength = Math.max(this._actionMaxLength, actionLength);
|
||||
|
||||
// add the item to the list
|
||||
this._addItem(this._formatAction, [ action ]);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* HelpFormatter#addArguments(actions) -> Void
|
||||
* - actions (array): actions list
|
||||
*
|
||||
* Mass add arguments into current section
|
||||
*
|
||||
* ##### Example
|
||||
*
|
||||
* formatter.startSection(actionGroup.title);
|
||||
* formatter.addText(actionGroup.description);
|
||||
* formatter.addArguments(actionGroup._groupActions);
|
||||
* formatter.endSection();
|
||||
*
|
||||
**/
|
||||
HelpFormatter.prototype.addArguments = function (actions) {
|
||||
var self = this;
|
||||
actions.forEach(function (action) {
|
||||
self.addArgument(action);
|
||||
});
|
||||
};
|
||||
|
||||
//
|
||||
// Help-formatting methods
|
||||
//
|
||||
|
||||
/**
|
||||
* HelpFormatter#formatHelp -> string
|
||||
*
|
||||
* Format help
|
||||
*
|
||||
* ##### Example
|
||||
*
|
||||
* formatter.addText(this.epilog);
|
||||
* return formatter.formatHelp();
|
||||
*
|
||||
**/
|
||||
HelpFormatter.prototype.formatHelp = function () {
|
||||
var help = this._rootSection.formatHelp(this);
|
||||
if (help) {
|
||||
help = help.replace(this._longBreakMatcher, c.EOL + c.EOL);
|
||||
help = $$.trimChars(help, c.EOL) + c.EOL;
|
||||
}
|
||||
return help;
|
||||
};
|
||||
|
||||
HelpFormatter.prototype._joinParts = function (partStrings) {
|
||||
return partStrings.filter(function (part) {
|
||||
return (part && part !== c.SUPPRESS);
|
||||
}).join('');
|
||||
};
|
||||
|
||||
HelpFormatter.prototype._formatUsage = function (usage, actions, groups, prefix) {
|
||||
if (!prefix && typeof prefix !== 'string') {
|
||||
prefix = 'usage: ';
|
||||
}
|
||||
|
||||
actions = actions || [];
|
||||
groups = groups || [];
|
||||
|
||||
|
||||
// if usage is specified, use that
|
||||
if (usage) {
|
||||
usage = sprintf(usage, { prog: this._prog });
|
||||
|
||||
// if no optionals or positionals are available, usage is just prog
|
||||
} else if (!usage && actions.length === 0) {
|
||||
usage = this._prog;
|
||||
|
||||
// if optionals and positionals are available, calculate usage
|
||||
} else if (!usage) {
|
||||
var prog = this._prog;
|
||||
var optionals = [];
|
||||
var positionals = [];
|
||||
var actionUsage;
|
||||
var textWidth;
|
||||
|
||||
// split optionals from positionals
|
||||
actions.forEach(function (action) {
|
||||
if (action.isOptional()) {
|
||||
optionals.push(action);
|
||||
} else {
|
||||
positionals.push(action);
|
||||
}
|
||||
});
|
||||
|
||||
// build full usage string
|
||||
actionUsage = this._formatActionsUsage([].concat(optionals, positionals), groups);
|
||||
usage = [ prog, actionUsage ].join(' ');
|
||||
|
||||
// wrap the usage parts if it's too long
|
||||
textWidth = this._width - this._currentIndent;
|
||||
if ((prefix.length + usage.length) > textWidth) {
|
||||
|
||||
// break usage into wrappable parts
|
||||
var regexpPart = new RegExp('\\(.*?\\)+|\\[.*?\\]+|\\S+', 'g');
|
||||
var optionalUsage = this._formatActionsUsage(optionals, groups);
|
||||
var positionalUsage = this._formatActionsUsage(positionals, groups);
|
||||
|
||||
|
||||
var optionalParts = optionalUsage.match(regexpPart);
|
||||
var positionalParts = positionalUsage.match(regexpPart) || [];
|
||||
|
||||
if (optionalParts.join(' ') !== optionalUsage) {
|
||||
throw new Error('assert "optionalParts.join(\' \') === optionalUsage"');
|
||||
}
|
||||
if (positionalParts.join(' ') !== positionalUsage) {
|
||||
throw new Error('assert "positionalParts.join(\' \') === positionalUsage"');
|
||||
}
|
||||
|
||||
// helper for wrapping lines
|
||||
/*eslint-disable func-style*/ // node 0.10 compat
|
||||
var _getLines = function (parts, indent, prefix) {
|
||||
var lines = [];
|
||||
var line = [];
|
||||
|
||||
var lineLength = prefix ? prefix.length - 1 : indent.length - 1;
|
||||
|
||||
parts.forEach(function (part) {
|
||||
if (lineLength + 1 + part.length > textWidth) {
|
||||
lines.push(indent + line.join(' '));
|
||||
line = [];
|
||||
lineLength = indent.length - 1;
|
||||
}
|
||||
line.push(part);
|
||||
lineLength += part.length + 1;
|
||||
});
|
||||
|
||||
if (line) {
|
||||
lines.push(indent + line.join(' '));
|
||||
}
|
||||
if (prefix) {
|
||||
lines[0] = lines[0].substr(indent.length);
|
||||
}
|
||||
return lines;
|
||||
};
|
||||
|
||||
var lines, indent, parts;
|
||||
// if prog is short, follow it with optionals or positionals
|
||||
if (prefix.length + prog.length <= 0.75 * textWidth) {
|
||||
indent = $$.repeat(' ', (prefix.length + prog.length + 1));
|
||||
if (optionalParts) {
|
||||
lines = [].concat(
|
||||
_getLines([ prog ].concat(optionalParts), indent, prefix),
|
||||
_getLines(positionalParts, indent)
|
||||
);
|
||||
} else if (positionalParts) {
|
||||
lines = _getLines([ prog ].concat(positionalParts), indent, prefix);
|
||||
} else {
|
||||
lines = [ prog ];
|
||||
}
|
||||
|
||||
// if prog is long, put it on its own line
|
||||
} else {
|
||||
indent = $$.repeat(' ', prefix.length);
|
||||
parts = optionalParts.concat(positionalParts);
|
||||
lines = _getLines(parts, indent);
|
||||
if (lines.length > 1) {
|
||||
lines = [].concat(
|
||||
_getLines(optionalParts, indent),
|
||||
_getLines(positionalParts, indent)
|
||||
);
|
||||
}
|
||||
lines = [ prog ].concat(lines);
|
||||
}
|
||||
// join lines into usage
|
||||
usage = lines.join(c.EOL);
|
||||
}
|
||||
}
|
||||
|
||||
// prefix with 'usage:'
|
||||
return prefix + usage + c.EOL + c.EOL;
|
||||
};
|
||||
|
||||
HelpFormatter.prototype._formatActionsUsage = function (actions, groups) {
|
||||
// find group indices and identify actions in groups
|
||||
var groupActions = [];
|
||||
var inserts = [];
|
||||
var self = this;
|
||||
|
||||
groups.forEach(function (group) {
|
||||
var end;
|
||||
var i;
|
||||
|
||||
var start = actions.indexOf(group._groupActions[0]);
|
||||
if (start >= 0) {
|
||||
end = start + group._groupActions.length;
|
||||
|
||||
//if (actions.slice(start, end) === group._groupActions) {
|
||||
if ($$.arrayEqual(actions.slice(start, end), group._groupActions)) {
|
||||
group._groupActions.forEach(function (action) {
|
||||
groupActions.push(action);
|
||||
});
|
||||
|
||||
if (!group.required) {
|
||||
if (inserts[start]) {
|
||||
inserts[start] += ' [';
|
||||
} else {
|
||||
inserts[start] = '[';
|
||||
}
|
||||
inserts[end] = ']';
|
||||
} else {
|
||||
if (inserts[start]) {
|
||||
inserts[start] += ' (';
|
||||
} else {
|
||||
inserts[start] = '(';
|
||||
}
|
||||
inserts[end] = ')';
|
||||
}
|
||||
for (i = start + 1; i < end; i += 1) {
|
||||
inserts[i] = '|';
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// collect all actions format strings
|
||||
var parts = [];
|
||||
|
||||
actions.forEach(function (action, actionIndex) {
|
||||
var part;
|
||||
var optionString;
|
||||
var argsDefault;
|
||||
var argsString;
|
||||
|
||||
// suppressed arguments are marked with None
|
||||
// remove | separators for suppressed arguments
|
||||
if (action.help === c.SUPPRESS) {
|
||||
parts.push(null);
|
||||
if (inserts[actionIndex] === '|') {
|
||||
inserts.splice(actionIndex, actionIndex);
|
||||
} else if (inserts[actionIndex + 1] === '|') {
|
||||
inserts.splice(actionIndex + 1, actionIndex + 1);
|
||||
}
|
||||
|
||||
// produce all arg strings
|
||||
} else if (!action.isOptional()) {
|
||||
part = self._formatArgs(action, action.dest);
|
||||
|
||||
// if it's in a group, strip the outer []
|
||||
if (groupActions.indexOf(action) >= 0) {
|
||||
if (part[0] === '[' && part[part.length - 1] === ']') {
|
||||
part = part.slice(1, -1);
|
||||
}
|
||||
}
|
||||
// add the action string to the list
|
||||
parts.push(part);
|
||||
|
||||
// produce the first way to invoke the option in brackets
|
||||
} else {
|
||||
optionString = action.optionStrings[0];
|
||||
|
||||
// if the Optional doesn't take a value, format is: -s or --long
|
||||
if (action.nargs === 0) {
|
||||
part = '' + optionString;
|
||||
|
||||
// if the Optional takes a value, format is: -s ARGS or --long ARGS
|
||||
} else {
|
||||
argsDefault = action.dest.toUpperCase();
|
||||
argsString = self._formatArgs(action, argsDefault);
|
||||
part = optionString + ' ' + argsString;
|
||||
}
|
||||
// make it look optional if it's not required or in a group
|
||||
if (!action.required && groupActions.indexOf(action) < 0) {
|
||||
part = '[' + part + ']';
|
||||
}
|
||||
// add the action string to the list
|
||||
parts.push(part);
|
||||
}
|
||||
});
|
||||
|
||||
// insert things at the necessary indices
|
||||
for (var i = inserts.length - 1; i >= 0; --i) {
|
||||
if (inserts[i] !== null) {
|
||||
parts.splice(i, 0, inserts[i]);
|
||||
}
|
||||
}
|
||||
|
||||
// join all the action items with spaces
|
||||
var text = parts.filter(function (part) {
|
||||
return !!part;
|
||||
}).join(' ');
|
||||
|
||||
// clean up separators for mutually exclusive groups
|
||||
text = text.replace(/([\[(]) /g, '$1'); // remove spaces
|
||||
text = text.replace(/ ([\])])/g, '$1');
|
||||
text = text.replace(/\[ *\]/g, ''); // remove empty groups
|
||||
text = text.replace(/\( *\)/g, '');
|
||||
text = text.replace(/\(([^|]*)\)/g, '$1'); // remove () from single action groups
|
||||
|
||||
text = text.trim();
|
||||
|
||||
// return the text
|
||||
return text;
|
||||
};
|
||||
|
||||
HelpFormatter.prototype._formatText = function (text) {
|
||||
text = sprintf(text, { prog: this._prog });
|
||||
var textWidth = this._width - this._currentIndent;
|
||||
var indentIncriment = $$.repeat(' ', this._currentIndent);
|
||||
return this._fillText(text, textWidth, indentIncriment) + c.EOL + c.EOL;
|
||||
};
|
||||
|
||||
HelpFormatter.prototype._formatAction = function (action) {
|
||||
var self = this;
|
||||
|
||||
var helpText;
|
||||
var helpLines;
|
||||
var parts;
|
||||
var indentFirst;
|
||||
|
||||
// determine the required width and the entry label
|
||||
var helpPosition = Math.min(this._actionMaxLength + 2, this._maxHelpPosition);
|
||||
var helpWidth = this._width - helpPosition;
|
||||
var actionWidth = helpPosition - this._currentIndent - 2;
|
||||
var actionHeader = this._formatActionInvocation(action);
|
||||
|
||||
// no help; start on same line and add a final newline
|
||||
if (!action.help) {
|
||||
actionHeader = $$.repeat(' ', this._currentIndent) + actionHeader + c.EOL;
|
||||
|
||||
// short action name; start on the same line and pad two spaces
|
||||
} else if (actionHeader.length <= actionWidth) {
|
||||
actionHeader = $$.repeat(' ', this._currentIndent) +
|
||||
actionHeader +
|
||||
' ' +
|
||||
$$.repeat(' ', actionWidth - actionHeader.length);
|
||||
indentFirst = 0;
|
||||
|
||||
// long action name; start on the next line
|
||||
} else {
|
||||
actionHeader = $$.repeat(' ', this._currentIndent) + actionHeader + c.EOL;
|
||||
indentFirst = helpPosition;
|
||||
}
|
||||
|
||||
// collect the pieces of the action help
|
||||
parts = [ actionHeader ];
|
||||
|
||||
// if there was help for the action, add lines of help text
|
||||
if (action.help) {
|
||||
helpText = this._expandHelp(action);
|
||||
helpLines = this._splitLines(helpText, helpWidth);
|
||||
parts.push($$.repeat(' ', indentFirst) + helpLines[0] + c.EOL);
|
||||
helpLines.slice(1).forEach(function (line) {
|
||||
parts.push($$.repeat(' ', helpPosition) + line + c.EOL);
|
||||
});
|
||||
|
||||
// or add a newline if the description doesn't end with one
|
||||
} else if (actionHeader.charAt(actionHeader.length - 1) !== c.EOL) {
|
||||
parts.push(c.EOL);
|
||||
}
|
||||
// if there are any sub-actions, add their help as well
|
||||
if (action._getSubactions) {
|
||||
this._indent();
|
||||
action._getSubactions().forEach(function (subaction) {
|
||||
parts.push(self._formatAction(subaction));
|
||||
});
|
||||
this._dedent();
|
||||
}
|
||||
// return a single string
|
||||
return this._joinParts(parts);
|
||||
};
|
||||
|
||||
HelpFormatter.prototype._formatActionInvocation = function (action) {
|
||||
if (!action.isOptional()) {
|
||||
var format_func = this._metavarFormatter(action, action.dest);
|
||||
var metavars = format_func(1);
|
||||
return metavars[0];
|
||||
}
|
||||
|
||||
var parts = [];
|
||||
var argsDefault;
|
||||
var argsString;
|
||||
|
||||
// if the Optional doesn't take a value, format is: -s, --long
|
||||
if (action.nargs === 0) {
|
||||
parts = parts.concat(action.optionStrings);
|
||||
|
||||
// if the Optional takes a value, format is: -s ARGS, --long ARGS
|
||||
} else {
|
||||
argsDefault = action.dest.toUpperCase();
|
||||
argsString = this._formatArgs(action, argsDefault);
|
||||
action.optionStrings.forEach(function (optionString) {
|
||||
parts.push(optionString + ' ' + argsString);
|
||||
});
|
||||
}
|
||||
return parts.join(', ');
|
||||
};
|
||||
|
||||
HelpFormatter.prototype._metavarFormatter = function (action, metavarDefault) {
|
||||
var result;
|
||||
|
||||
if (action.metavar || action.metavar === '') {
|
||||
result = action.metavar;
|
||||
} else if (action.choices) {
|
||||
var choices = action.choices;
|
||||
|
||||
if (typeof choices === 'string') {
|
||||
choices = choices.split('').join(', ');
|
||||
} else if (Array.isArray(choices)) {
|
||||
choices = choices.join(',');
|
||||
} else {
|
||||
choices = Object.keys(choices).join(',');
|
||||
}
|
||||
result = '{' + choices + '}';
|
||||
} else {
|
||||
result = metavarDefault;
|
||||
}
|
||||
|
||||
return function (size) {
|
||||
if (Array.isArray(result)) {
|
||||
return result;
|
||||
}
|
||||
|
||||
var metavars = [];
|
||||
for (var i = 0; i < size; i += 1) {
|
||||
metavars.push(result);
|
||||
}
|
||||
return metavars;
|
||||
};
|
||||
};
|
||||
|
||||
HelpFormatter.prototype._formatArgs = function (action, metavarDefault) {
|
||||
var result;
|
||||
var metavars;
|
||||
|
||||
var buildMetavar = this._metavarFormatter(action, metavarDefault);
|
||||
|
||||
switch (action.nargs) {
|
||||
/*eslint-disable no-undefined*/
|
||||
case undefined:
|
||||
case null:
|
||||
metavars = buildMetavar(1);
|
||||
result = '' + metavars[0];
|
||||
break;
|
||||
case c.OPTIONAL:
|
||||
metavars = buildMetavar(1);
|
||||
result = '[' + metavars[0] + ']';
|
||||
break;
|
||||
case c.ZERO_OR_MORE:
|
||||
metavars = buildMetavar(2);
|
||||
result = '[' + metavars[0] + ' [' + metavars[1] + ' ...]]';
|
||||
break;
|
||||
case c.ONE_OR_MORE:
|
||||
metavars = buildMetavar(2);
|
||||
result = '' + metavars[0] + ' [' + metavars[1] + ' ...]';
|
||||
break;
|
||||
case c.REMAINDER:
|
||||
result = '...';
|
||||
break;
|
||||
case c.PARSER:
|
||||
metavars = buildMetavar(1);
|
||||
result = metavars[0] + ' ...';
|
||||
break;
|
||||
default:
|
||||
metavars = buildMetavar(action.nargs);
|
||||
result = metavars.join(' ');
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
HelpFormatter.prototype._expandHelp = function (action) {
|
||||
var params = { prog: this._prog };
|
||||
|
||||
Object.keys(action).forEach(function (actionProperty) {
|
||||
var actionValue = action[actionProperty];
|
||||
|
||||
if (actionValue !== c.SUPPRESS) {
|
||||
params[actionProperty] = actionValue;
|
||||
}
|
||||
});
|
||||
|
||||
if (params.choices) {
|
||||
if (typeof params.choices === 'string') {
|
||||
params.choices = params.choices.split('').join(', ');
|
||||
} else if (Array.isArray(params.choices)) {
|
||||
params.choices = params.choices.join(', ');
|
||||
} else {
|
||||
params.choices = Object.keys(params.choices).join(', ');
|
||||
}
|
||||
}
|
||||
|
||||
return sprintf(this._getHelpString(action), params);
|
||||
};
|
||||
|
||||
HelpFormatter.prototype._splitLines = function (text, width) {
|
||||
var lines = [];
|
||||
var delimiters = [ ' ', '.', ',', '!', '?' ];
|
||||
var re = new RegExp('[' + delimiters.join('') + '][^' + delimiters.join('') + ']*$');
|
||||
|
||||
text = text.replace(/[\n\|\t]/g, ' ');
|
||||
|
||||
text = text.trim();
|
||||
text = text.replace(this._whitespaceMatcher, ' ');
|
||||
|
||||
// Wraps the single paragraph in text (a string) so every line
|
||||
// is at most width characters long.
|
||||
text.split(c.EOL).forEach(function (line) {
|
||||
if (width >= line.length) {
|
||||
lines.push(line);
|
||||
return;
|
||||
}
|
||||
|
||||
var wrapStart = 0;
|
||||
var wrapEnd = width;
|
||||
var delimiterIndex = 0;
|
||||
while (wrapEnd <= line.length) {
|
||||
if (wrapEnd !== line.length && delimiters.indexOf(line[wrapEnd] < -1)) {
|
||||
delimiterIndex = (re.exec(line.substring(wrapStart, wrapEnd)) || {}).index;
|
||||
wrapEnd = wrapStart + delimiterIndex + 1;
|
||||
}
|
||||
lines.push(line.substring(wrapStart, wrapEnd));
|
||||
wrapStart = wrapEnd;
|
||||
wrapEnd += width;
|
||||
}
|
||||
if (wrapStart < line.length) {
|
||||
lines.push(line.substring(wrapStart, wrapEnd));
|
||||
}
|
||||
});
|
||||
|
||||
return lines;
|
||||
};
|
||||
|
||||
HelpFormatter.prototype._fillText = function (text, width, indent) {
|
||||
var lines = this._splitLines(text, width);
|
||||
lines = lines.map(function (line) {
|
||||
return indent + line;
|
||||
});
|
||||
return lines.join(c.EOL);
|
||||
};
|
||||
|
||||
HelpFormatter.prototype._getHelpString = function (action) {
|
||||
return action.help;
|
||||
};
|
@ -0,0 +1,76 @@
|
||||
/**
|
||||
* class Namespace
|
||||
*
|
||||
* Simple object for storing attributes. Implements equality by attribute names
|
||||
* and values, and provides a simple string representation.
|
||||
*
|
||||
* See also [original guide][1]
|
||||
*
|
||||
* [1]:http://docs.python.org/dev/library/argparse.html#the-namespace-object
|
||||
**/
|
||||
'use strict';
|
||||
|
||||
var $$ = require('./utils');
|
||||
|
||||
/**
|
||||
* new Namespace(options)
|
||||
* - options(object): predefined propertis for result object
|
||||
*
|
||||
**/
|
||||
var Namespace = module.exports = function Namespace(options) {
|
||||
$$.extend(this, options);
|
||||
};
|
||||
|
||||
/**
|
||||
* Namespace#isset(key) -> Boolean
|
||||
* - key (string|number): property name
|
||||
*
|
||||
* Tells whenever `namespace` contains given `key` or not.
|
||||
**/
|
||||
Namespace.prototype.isset = function (key) {
|
||||
return $$.has(this, key);
|
||||
};
|
||||
|
||||
/**
|
||||
* Namespace#set(key, value) -> self
|
||||
* -key (string|number|object): propery name
|
||||
* -value (mixed): new property value
|
||||
*
|
||||
* Set the property named key with value.
|
||||
* If key object then set all key properties to namespace object
|
||||
**/
|
||||
Namespace.prototype.set = function (key, value) {
|
||||
if (typeof (key) === 'object') {
|
||||
$$.extend(this, key);
|
||||
} else {
|
||||
this[key] = value;
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Namespace#get(key, defaultValue) -> mixed
|
||||
* - key (string|number): property name
|
||||
* - defaultValue (mixed): default value
|
||||
*
|
||||
* Return the property key or defaulValue if not set
|
||||
**/
|
||||
Namespace.prototype.get = function (key, defaultValue) {
|
||||
return !this[key] ? defaultValue : this[key];
|
||||
};
|
||||
|
||||
/**
|
||||
* Namespace#unset(key, defaultValue) -> mixed
|
||||
* - key (string|number): property name
|
||||
* - defaultValue (mixed): default value
|
||||
*
|
||||
* Return data[key](and delete it) or defaultValue
|
||||
**/
|
||||
Namespace.prototype.unset = function (key, defaultValue) {
|
||||
var value = this[key];
|
||||
if (value !== null) {
|
||||
delete this[key];
|
||||
return value;
|
||||
}
|
||||
return defaultValue;
|
||||
};
|
@ -0,0 +1,57 @@
|
||||
'use strict';
|
||||
|
||||
exports.repeat = function (str, num) {
|
||||
var result = '';
|
||||
for (var i = 0; i < num; i++) { result += str; }
|
||||
return result;
|
||||
};
|
||||
|
||||
exports.arrayEqual = function (a, b) {
|
||||
if (a.length !== b.length) { return false; }
|
||||
for (var i = 0; i < a.length; i++) {
|
||||
if (a[i] !== b[i]) { return false; }
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
exports.trimChars = function (str, chars) {
|
||||
var start = 0;
|
||||
var end = str.length - 1;
|
||||
while (chars.indexOf(str.charAt(start)) >= 0) { start++; }
|
||||
while (chars.indexOf(str.charAt(end)) >= 0) { end--; }
|
||||
return str.slice(start, end + 1);
|
||||
};
|
||||
|
||||
exports.capitalize = function (str) {
|
||||
return str.charAt(0).toUpperCase() + str.slice(1);
|
||||
};
|
||||
|
||||
exports.arrayUnion = function () {
|
||||
var result = [];
|
||||
for (var i = 0, values = {}; i < arguments.length; i++) {
|
||||
var arr = arguments[i];
|
||||
for (var j = 0; j < arr.length; j++) {
|
||||
if (!values[arr[j]]) {
|
||||
values[arr[j]] = true;
|
||||
result.push(arr[j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
function has(obj, key) {
|
||||
return Object.prototype.hasOwnProperty.call(obj, key);
|
||||
}
|
||||
|
||||
exports.has = has;
|
||||
|
||||
exports.extend = function (dest, src) {
|
||||
for (var i in src) {
|
||||
if (has(src, i)) { dest[i] = src[i]; }
|
||||
}
|
||||
};
|
||||
|
||||
exports.trimEnd = function (str) {
|
||||
return str.replace(/\s+$/g, '');
|
||||
};
|
@ -0,0 +1,70 @@
|
||||
{
|
||||
"_from": "argparse@^1.0.7",
|
||||
"_id": "argparse@1.0.10",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==",
|
||||
"_location": "/argparse",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "argparse@^1.0.7",
|
||||
"name": "argparse",
|
||||
"escapedName": "argparse",
|
||||
"rawSpec": "^1.0.7",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "^1.0.7"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/yamljs"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz",
|
||||
"_shasum": "bcd6791ea5ae09725e17e5ad988134cd40b3d911",
|
||||
"_spec": "argparse@^1.0.7",
|
||||
"_where": "/Users/paolo/Desktop/multiplayer games/likelike-online/node_modules/yamljs",
|
||||
"bugs": {
|
||||
"url": "https://github.com/nodeca/argparse/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"contributors": [
|
||||
{
|
||||
"name": "Eugene Shkuropat"
|
||||
},
|
||||
{
|
||||
"name": "Paul Jacobson"
|
||||
}
|
||||
],
|
||||
"dependencies": {
|
||||
"sprintf-js": "~1.0.2"
|
||||
},
|
||||
"deprecated": false,
|
||||
"description": "Very powerful CLI arguments parser. Native port of argparse - python's options parsing library",
|
||||
"devDependencies": {
|
||||
"eslint": "^2.13.1",
|
||||
"istanbul": "^0.4.5",
|
||||
"mocha": "^3.1.0",
|
||||
"ndoc": "^5.0.1"
|
||||
},
|
||||
"files": [
|
||||
"index.js",
|
||||
"lib/"
|
||||
],
|
||||
"homepage": "https://github.com/nodeca/argparse#readme",
|
||||
"keywords": [
|
||||
"cli",
|
||||
"parser",
|
||||
"argparse",
|
||||
"option",
|
||||
"args"
|
||||
],
|
||||
"license": "MIT",
|
||||
"name": "argparse",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/nodeca/argparse.git"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "make test"
|
||||
},
|
||||
"version": "1.0.10"
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
test
|
||||
.gitignore
|
||||
.travis.yml
|
||||
Makefile
|
||||
example.js
|
@ -0,0 +1,21 @@
|
||||
(MIT)
|
||||
|
||||
Copyright (c) 2013 Julian Gruber <julian@juliangruber.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the "Software"), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do
|
||||
so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
@ -0,0 +1,91 @@
|
||||
# balanced-match
|
||||
|
||||
Match balanced string pairs, like `{` and `}` or `<b>` and `</b>`. Supports regular expressions as well!
|
||||
|
||||
[![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match)
|
||||
[![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match)
|
||||
|
||||
[![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match)
|
||||
|
||||
## Example
|
||||
|
||||
Get the first matching pair of braces:
|
||||
|
||||
```js
|
||||
var balanced = require('balanced-match');
|
||||
|
||||
console.log(balanced('{', '}', 'pre{in{nested}}post'));
|
||||
console.log(balanced('{', '}', 'pre{first}between{second}post'));
|
||||
console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post'));
|
||||
```
|
||||
|
||||
The matches are:
|
||||
|
||||
```bash
|
||||
$ node example.js
|
||||
{ start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' }
|
||||
{ start: 3,
|
||||
end: 9,
|
||||
pre: 'pre',
|
||||
body: 'first',
|
||||
post: 'between{second}post' }
|
||||
{ start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' }
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
### var m = balanced(a, b, str)
|
||||
|
||||
For the first non-nested matching pair of `a` and `b` in `str`, return an
|
||||
object with those keys:
|
||||
|
||||
* **start** the index of the first match of `a`
|
||||
* **end** the index of the matching `b`
|
||||
* **pre** the preamble, `a` and `b` not included
|
||||
* **body** the match, `a` and `b` not included
|
||||
* **post** the postscript, `a` and `b` not included
|
||||
|
||||
If there's no match, `undefined` will be returned.
|
||||
|
||||
If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`.
|
||||
|
||||
### var r = balanced.range(a, b, str)
|
||||
|
||||
For the first non-nested matching pair of `a` and `b` in `str`, return an
|
||||
array with indexes: `[ <a index>, <b index> ]`.
|
||||
|
||||
If there's no match, `undefined` will be returned.
|
||||
|
||||
If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`.
|
||||
|
||||
## Installation
|
||||
|
||||
With [npm](https://npmjs.org) do:
|
||||
|
||||
```bash
|
||||
npm install balanced-match
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
(MIT)
|
||||
|
||||
Copyright (c) 2013 Julian Gruber <julian@juliangruber.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the "Software"), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do
|
||||
so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
@ -0,0 +1,59 @@
|
||||
'use strict';
|
||||
module.exports = balanced;
|
||||
function balanced(a, b, str) {
|
||||
if (a instanceof RegExp) a = maybeMatch(a, str);
|
||||
if (b instanceof RegExp) b = maybeMatch(b, str);
|
||||
|
||||
var r = range(a, b, str);
|
||||
|
||||
return r && {
|
||||
start: r[0],
|
||||
end: r[1],
|
||||
pre: str.slice(0, r[0]),
|
||||
body: str.slice(r[0] + a.length, r[1]),
|
||||
post: str.slice(r[1] + b.length)
|
||||
};
|
||||
}
|
||||
|
||||
function maybeMatch(reg, str) {
|
||||
var m = str.match(reg);
|
||||
return m ? m[0] : null;
|
||||
}
|
||||
|
||||
balanced.range = range;
|
||||
function range(a, b, str) {
|
||||
var begs, beg, left, right, result;
|
||||
var ai = str.indexOf(a);
|
||||
var bi = str.indexOf(b, ai + 1);
|
||||
var i = ai;
|
||||
|
||||
if (ai >= 0 && bi > 0) {
|
||||
begs = [];
|
||||
left = str.length;
|
||||
|
||||
while (i >= 0 && !result) {
|
||||
if (i == ai) {
|
||||
begs.push(i);
|
||||
ai = str.indexOf(a, i + 1);
|
||||
} else if (begs.length == 1) {
|
||||
result = [ begs.pop(), bi ];
|
||||
} else {
|
||||
beg = begs.pop();
|
||||
if (beg < left) {
|
||||
left = beg;
|
||||
right = bi;
|
||||
}
|
||||
|
||||
bi = str.indexOf(b, i + 1);
|
||||
}
|
||||
|
||||
i = ai < bi && ai >= 0 ? ai : bi;
|
||||
}
|
||||
|
||||
if (begs.length) {
|
||||
result = [ left, right ];
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
@ -0,0 +1,77 @@
|
||||
{
|
||||
"_from": "balanced-match@^1.0.0",
|
||||
"_id": "balanced-match@1.0.0",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=",
|
||||
"_location": "/balanced-match",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "balanced-match@^1.0.0",
|
||||
"name": "balanced-match",
|
||||
"escapedName": "balanced-match",
|
||||
"rawSpec": "^1.0.0",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "^1.0.0"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/brace-expansion"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz",
|
||||
"_shasum": "89b4d199ab2bee49de164ea02b89ce462d71b767",
|
||||
"_spec": "balanced-match@^1.0.0",
|
||||
"_where": "/Users/paolo/Desktop/multiplayer games/likelike-online/node_modules/brace-expansion",
|
||||
"author": {
|
||||
"name": "Julian Gruber",
|
||||
"email": "mail@juliangruber.com",
|
||||
"url": "http://juliangruber.com"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/juliangruber/balanced-match/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"dependencies": {},
|
||||
"deprecated": false,
|
||||
"description": "Match balanced character pairs, like \"{\" and \"}\"",
|
||||
"devDependencies": {
|
||||
"matcha": "^0.7.0",
|
||||
"tape": "^4.6.0"
|
||||
},
|
||||
"homepage": "https://github.com/juliangruber/balanced-match",
|
||||
"keywords": [
|
||||
"match",
|
||||
"regexp",
|
||||
"test",
|
||||
"balanced",
|
||||
"parse"
|
||||
],
|
||||
"license": "MIT",
|
||||
"main": "index.js",
|
||||
"name": "balanced-match",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/juliangruber/balanced-match.git"
|
||||
},
|
||||
"scripts": {
|
||||
"bench": "make bench",
|
||||
"test": "make test"
|
||||
},
|
||||
"testling": {
|
||||
"files": "test/*.js",
|
||||
"browsers": [
|
||||
"ie/8..latest",
|
||||
"firefox/20..latest",
|
||||
"firefox/nightly",
|
||||
"chrome/25..latest",
|
||||
"chrome/canary",
|
||||
"opera/12..latest",
|
||||
"opera/next",
|
||||
"safari/5.1..latest",
|
||||
"ipad/6.0..latest",
|
||||
"iphone/6.0..latest",
|
||||
"android-browser/4.2..latest"
|
||||
]
|
||||
},
|
||||
"version": "1.0.0"
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2013 Julian Gruber <julian@juliangruber.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
@ -0,0 +1,129 @@
|
||||
# brace-expansion
|
||||
|
||||
[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html),
|
||||
as known from sh/bash, in JavaScript.
|
||||
|
||||
[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion)
|
||||
[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion)
|
||||
[![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/)
|
||||
|
||||
[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion)
|
||||
|
||||
## Example
|
||||
|
||||
```js
|
||||
var expand = require('brace-expansion');
|
||||
|
||||
expand('file-{a,b,c}.jpg')
|
||||
// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']
|
||||
|
||||
expand('-v{,,}')
|
||||
// => ['-v', '-v', '-v']
|
||||
|
||||
expand('file{0..2}.jpg')
|
||||
// => ['file0.jpg', 'file1.jpg', 'file2.jpg']
|
||||
|
||||
expand('file-{a..c}.jpg')
|
||||
// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']
|
||||
|
||||
expand('file{2..0}.jpg')
|
||||
// => ['file2.jpg', 'file1.jpg', 'file0.jpg']
|
||||
|
||||
expand('file{0..4..2}.jpg')
|
||||
// => ['file0.jpg', 'file2.jpg', 'file4.jpg']
|
||||
|
||||
expand('file-{a..e..2}.jpg')
|
||||
// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg']
|
||||
|
||||
expand('file{00..10..5}.jpg')
|
||||
// => ['file00.jpg', 'file05.jpg', 'file10.jpg']
|
||||
|
||||
expand('{{A..C},{a..c}}')
|
||||
// => ['A', 'B', 'C', 'a', 'b', 'c']
|
||||
|
||||
expand('ppp{,config,oe{,conf}}')
|
||||
// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf']
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
```js
|
||||
var expand = require('brace-expansion');
|
||||
```
|
||||
|
||||
### var expanded = expand(str)
|
||||
|
||||
Return an array of all possible and valid expansions of `str`. If none are
|
||||
found, `[str]` is returned.
|
||||
|
||||
Valid expansions are:
|
||||
|
||||
```js
|
||||
/^(.*,)+(.+)?$/
|
||||
// {a,b,...}
|
||||
```
|
||||
|
||||
A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`.
|
||||
|
||||
```js
|
||||
/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/
|
||||
// {x..y[..incr]}
|
||||
```
|
||||
|
||||
A numeric sequence from `x` to `y` inclusive, with optional increment.
|
||||
If `x` or `y` start with a leading `0`, all the numbers will be padded
|
||||
to have equal length. Negative numbers and backwards iteration work too.
|
||||
|
||||
```js
|
||||
/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/
|
||||
// {x..y[..incr]}
|
||||
```
|
||||
|
||||
An alphabetic sequence from `x` to `y` inclusive, with optional increment.
|
||||
`x` and `y` must be exactly one character, and if given, `incr` must be a
|
||||
number.
|
||||
|
||||
For compatibility reasons, the string `${` is not eligible for brace expansion.
|
||||
|
||||
## Installation
|
||||
|
||||
With [npm](https://npmjs.org) do:
|
||||
|
||||
```bash
|
||||
npm install brace-expansion
|
||||
```
|
||||
|
||||
## Contributors
|
||||
|
||||
- [Julian Gruber](https://github.com/juliangruber)
|
||||
- [Isaac Z. Schlueter](https://github.com/isaacs)
|
||||
|
||||
## Sponsors
|
||||
|
||||
This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)!
|
||||
|
||||
Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)!
|
||||
|
||||
## License
|
||||
|
||||
(MIT)
|
||||
|
||||
Copyright (c) 2013 Julian Gruber <julian@juliangruber.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the "Software"), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do
|
||||
so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
@ -0,0 +1,201 @@
|
||||
var concatMap = require('concat-map');
|
||||
var balanced = require('balanced-match');
|
||||
|
||||
module.exports = expandTop;
|
||||
|
||||
var escSlash = '\0SLASH'+Math.random()+'\0';
|
||||
var escOpen = '\0OPEN'+Math.random()+'\0';
|
||||
var escClose = '\0CLOSE'+Math.random()+'\0';
|
||||
var escComma = '\0COMMA'+Math.random()+'\0';
|
||||
var escPeriod = '\0PERIOD'+Math.random()+'\0';
|
||||
|
||||
function numeric(str) {
|
||||
return parseInt(str, 10) == str
|
||||
? parseInt(str, 10)
|
||||
: str.charCodeAt(0);
|
||||
}
|
||||
|
||||
function escapeBraces(str) {
|
||||
return str.split('\\\\').join(escSlash)
|
||||
.split('\\{').join(escOpen)
|
||||
.split('\\}').join(escClose)
|
||||
.split('\\,').join(escComma)
|
||||
.split('\\.').join(escPeriod);
|
||||
}
|
||||
|
||||
function unescapeBraces(str) {
|
||||
return str.split(escSlash).join('\\')
|
||||
.split(escOpen).join('{')
|
||||
.split(escClose).join('}')
|
||||
.split(escComma).join(',')
|
||||
.split(escPeriod).join('.');
|
||||
}
|
||||
|
||||
|
||||
// Basically just str.split(","), but handling cases
|
||||
// where we have nested braced sections, which should be
|
||||
// treated as individual members, like {a,{b,c},d}
|
||||
function parseCommaParts(str) {
|
||||
if (!str)
|
||||
return [''];
|
||||
|
||||
var parts = [];
|
||||
var m = balanced('{', '}', str);
|
||||
|
||||
if (!m)
|
||||
return str.split(',');
|
||||
|
||||
var pre = m.pre;
|
||||
var body = m.body;
|
||||
var post = m.post;
|
||||
var p = pre.split(',');
|
||||
|
||||
p[p.length-1] += '{' + body + '}';
|
||||
var postParts = parseCommaParts(post);
|
||||
if (post.length) {
|
||||
p[p.length-1] += postParts.shift();
|
||||
p.push.apply(p, postParts);
|
||||
}
|
||||
|
||||
parts.push.apply(parts, p);
|
||||
|
||||
return parts;
|
||||
}
|
||||
|
||||
function expandTop(str) {
|
||||
if (!str)
|
||||
return [];
|
||||
|
||||
// I don't know why Bash 4.3 does this, but it does.
|
||||
// Anything starting with {} will have the first two bytes preserved
|
||||
// but *only* at the top level, so {},a}b will not expand to anything,
|
||||
// but a{},b}c will be expanded to [a}c,abc].
|
||||
// One could argue that this is a bug in Bash, but since the goal of
|
||||
// this module is to match Bash's rules, we escape a leading {}
|
||||
if (str.substr(0, 2) === '{}') {
|
||||
str = '\\{\\}' + str.substr(2);
|
||||
}
|
||||
|
||||
return expand(escapeBraces(str), true).map(unescapeBraces);
|
||||
}
|
||||
|
||||
function identity(e) {
|
||||
return e;
|
||||
}
|
||||
|
||||
function embrace(str) {
|
||||
return '{' + str + '}';
|
||||
}
|
||||
function isPadded(el) {
|
||||
return /^-?0\d/.test(el);
|
||||
}
|
||||
|
||||
function lte(i, y) {
|
||||
return i <= y;
|
||||
}
|
||||
function gte(i, y) {
|
||||
return i >= y;
|
||||
}
|
||||
|
||||
function expand(str, isTop) {
|
||||
var expansions = [];
|
||||
|
||||
var m = balanced('{', '}', str);
|
||||
if (!m || /\$$/.test(m.pre)) return [str];
|
||||
|
||||
var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
|
||||
var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
|
||||
var isSequence = isNumericSequence || isAlphaSequence;
|
||||
var isOptions = m.body.indexOf(',') >= 0;
|
||||
if (!isSequence && !isOptions) {
|
||||
// {a},b}
|
||||
if (m.post.match(/,.*\}/)) {
|
||||
str = m.pre + '{' + m.body + escClose + m.post;
|
||||
return expand(str);
|
||||
}
|
||||
return [str];
|
||||
}
|
||||
|
||||
var n;
|
||||
if (isSequence) {
|
||||
n = m.body.split(/\.\./);
|
||||
} else {
|
||||
n = parseCommaParts(m.body);
|
||||
if (n.length === 1) {
|
||||
// x{{a,b}}y ==> x{a}y x{b}y
|
||||
n = expand(n[0], false).map(embrace);
|
||||
if (n.length === 1) {
|
||||
var post = m.post.length
|
||||
? expand(m.post, false)
|
||||
: [''];
|
||||
return post.map(function(p) {
|
||||
return m.pre + n[0] + p;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// at this point, n is the parts, and we know it's not a comma set
|
||||
// with a single entry.
|
||||
|
||||
// no need to expand pre, since it is guaranteed to be free of brace-sets
|
||||
var pre = m.pre;
|
||||
var post = m.post.length
|
||||
? expand(m.post, false)
|
||||
: [''];
|
||||
|
||||
var N;
|
||||
|
||||
if (isSequence) {
|
||||
var x = numeric(n[0]);
|
||||
var y = numeric(n[1]);
|
||||
var width = Math.max(n[0].length, n[1].length)
|
||||
var incr = n.length == 3
|
||||
? Math.abs(numeric(n[2]))
|
||||
: 1;
|
||||
var test = lte;
|
||||
var reverse = y < x;
|
||||
if (reverse) {
|
||||
incr *= -1;
|
||||
test = gte;
|
||||
}
|
||||
var pad = n.some(isPadded);
|
||||
|
||||
N = [];
|
||||
|
||||
for (var i = x; test(i, y); i += incr) {
|
||||
var c;
|
||||
if (isAlphaSequence) {
|
||||
c = String.fromCharCode(i);
|
||||
if (c === '\\')
|
||||
c = '';
|
||||
} else {
|
||||
c = String(i);
|
||||
if (pad) {
|
||||
var need = width - c.length;
|
||||
if (need > 0) {
|
||||
var z = new Array(need + 1).join('0');
|
||||
if (i < 0)
|
||||
c = '-' + z + c.slice(1);
|
||||
else
|
||||
c = z + c;
|
||||
}
|
||||
}
|
||||
}
|
||||
N.push(c);
|
||||
}
|
||||
} else {
|
||||
N = concatMap(n, function(el) { return expand(el, false) });
|
||||
}
|
||||
|
||||
for (var j = 0; j < N.length; j++) {
|
||||
for (var k = 0; k < post.length; k++) {
|
||||
var expansion = pre + N[j] + post[k];
|
||||
if (!isTop || isSequence || expansion)
|
||||
expansions.push(expansion);
|
||||
}
|
||||
}
|
||||
|
||||
return expansions;
|
||||
}
|
||||
|
@ -0,0 +1,75 @@
|
||||
{
|
||||
"_from": "brace-expansion@^1.1.7",
|
||||
"_id": "brace-expansion@1.1.11",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
|
||||
"_location": "/brace-expansion",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "brace-expansion@^1.1.7",
|
||||
"name": "brace-expansion",
|
||||
"escapedName": "brace-expansion",
|
||||
"rawSpec": "^1.1.7",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "^1.1.7"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/minimatch"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
|
||||
"_shasum": "3c7fcbf529d87226f3d2f52b966ff5271eb441dd",
|
||||
"_spec": "brace-expansion@^1.1.7",
|
||||
"_where": "/Users/paolo/Desktop/multiplayer games/likelike-online/node_modules/minimatch",
|
||||
"author": {
|
||||
"name": "Julian Gruber",
|
||||
"email": "mail@juliangruber.com",
|
||||
"url": "http://juliangruber.com"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/juliangruber/brace-expansion/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"dependencies": {
|
||||
"balanced-match": "^1.0.0",
|
||||
"concat-map": "0.0.1"
|
||||
},
|
||||
"deprecated": false,
|
||||
"description": "Brace expansion as known from sh/bash",
|
||||
"devDependencies": {
|
||||
"matcha": "^0.7.0",
|
||||
"tape": "^4.6.0"
|
||||
},
|
||||
"homepage": "https://github.com/juliangruber/brace-expansion",
|
||||
"keywords": [],
|
||||
"license": "MIT",
|
||||
"main": "index.js",
|
||||
"name": "brace-expansion",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/juliangruber/brace-expansion.git"
|
||||
},
|
||||
"scripts": {
|
||||
"bench": "matcha test/perf/bench.js",
|
||||
"gentest": "bash test/generate.sh",
|
||||
"test": "tape test/*.js"
|
||||
},
|
||||
"testling": {
|
||||
"files": "test/*.js",
|
||||
"browsers": [
|
||||
"ie/8..latest",
|
||||
"firefox/20..latest",
|
||||
"firefox/nightly",
|
||||
"chrome/25..latest",
|
||||
"chrome/canary",
|
||||
"opera/12..latest",
|
||||
"opera/next",
|
||||
"safari/5.1..latest",
|
||||
"ipad/6.0..latest",
|
||||
"iphone/6.0..latest",
|
||||
"android-browser/4.2..latest"
|
||||
]
|
||||
},
|
||||
"version": "1.1.11"
|
||||
}
|
@ -0,0 +1,4 @@
|
||||
language: node_js
|
||||
node_js:
|
||||
- 0.4
|
||||
- 0.6
|
@ -0,0 +1,18 @@
|
||||
This software is released under the MIT license:
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the "Software"), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
@ -0,0 +1,62 @@
|
||||
concat-map
|
||||
==========
|
||||
|
||||
Concatenative mapdashery.
|
||||
|
||||
[![browser support](http://ci.testling.com/substack/node-concat-map.png)](http://ci.testling.com/substack/node-concat-map)
|
||||
|
||||
[![build status](https://secure.travis-ci.org/substack/node-concat-map.png)](http://travis-ci.org/substack/node-concat-map)
|
||||
|
||||
example
|
||||
=======
|
||||
|
||||
``` js
|
||||
var concatMap = require('concat-map');
|
||||
var xs = [ 1, 2, 3, 4, 5, 6 ];
|
||||
var ys = concatMap(xs, function (x) {
|
||||
return x % 2 ? [ x - 0.1, x, x + 0.1 ] : [];
|
||||
});
|
||||
console.dir(ys);
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
```
|
||||
[ 0.9, 1, 1.1, 2.9, 3, 3.1, 4.9, 5, 5.1 ]
|
||||
```
|
||||
|
||||
methods
|
||||
=======
|
||||
|
||||
``` js
|
||||
var concatMap = require('concat-map')
|
||||
```
|
||||
|
||||
concatMap(xs, fn)
|
||||
-----------------
|
||||
|
||||
Return an array of concatenated elements by calling `fn(x, i)` for each element
|
||||
`x` and each index `i` in the array `xs`.
|
||||
|
||||
When `fn(x, i)` returns an array, its result will be concatenated with the
|
||||
result array. If `fn(x, i)` returns anything else, that value will be pushed
|
||||
onto the end of the result array.
|
||||
|
||||
install
|
||||
=======
|
||||
|
||||
With [npm](http://npmjs.org) do:
|
||||
|
||||
```
|
||||
npm install concat-map
|
||||
```
|
||||
|
||||
license
|
||||
=======
|
||||
|
||||
MIT
|
||||
|
||||
notes
|
||||
=====
|
||||
|
||||
This module was written while sitting high above the ground in a tree.
|
@ -0,0 +1,6 @@
|
||||
var concatMap = require('../');
|
||||
var xs = [ 1, 2, 3, 4, 5, 6 ];
|
||||
var ys = concatMap(xs, function (x) {
|
||||
return x % 2 ? [ x - 0.1, x, x + 0.1 ] : [];
|
||||
});
|
||||
console.dir(ys);
|
@ -0,0 +1,13 @@
|
||||
module.exports = function (xs, fn) {
|
||||
var res = [];
|
||||
for (var i = 0; i < xs.length; i++) {
|
||||
var x = fn(xs[i], i);
|
||||
if (isArray(x)) res.push.apply(res, x);
|
||||
else res.push(x);
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
var isArray = Array.isArray || function (xs) {
|
||||
return Object.prototype.toString.call(xs) === '[object Array]';
|
||||
};
|
@ -0,0 +1,88 @@
|
||||
{
|
||||
"_from": "concat-map@0.0.1",
|
||||
"_id": "concat-map@0.0.1",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=",
|
||||
"_location": "/concat-map",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "version",
|
||||
"registry": true,
|
||||
"raw": "concat-map@0.0.1",
|
||||
"name": "concat-map",
|
||||
"escapedName": "concat-map",
|
||||
"rawSpec": "0.0.1",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "0.0.1"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/brace-expansion"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
|
||||
"_shasum": "d8a96bd77fd68df7793a73036a3ba0d5405d477b",
|
||||
"_spec": "concat-map@0.0.1",
|
||||
"_where": "/Users/paolo/Desktop/multiplayer games/likelike-online/node_modules/brace-expansion",
|
||||
"author": {
|
||||
"name": "James Halliday",
|
||||
"email": "mail@substack.net",
|
||||
"url": "http://substack.net"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/substack/node-concat-map/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"deprecated": false,
|
||||
"description": "concatenative mapdashery",
|
||||
"devDependencies": {
|
||||
"tape": "~2.4.0"
|
||||
},
|
||||
"directories": {
|
||||
"example": "example",
|
||||
"test": "test"
|
||||
},
|
||||
"homepage": "https://github.com/substack/node-concat-map#readme",
|
||||
"keywords": [
|
||||
"concat",
|
||||
"concatMap",
|
||||
"map",
|
||||
"functional",
|
||||
"higher-order"
|
||||
],
|
||||
"license": "MIT",
|
||||
"main": "index.js",
|
||||
"name": "concat-map",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/substack/node-concat-map.git"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "tape test/*.js"
|
||||
},
|
||||
"testling": {
|
||||
"files": "test/*.js",
|
||||
"browsers": {
|
||||
"ie": [
|
||||
6,
|
||||
7,
|
||||
8,
|
||||
9
|
||||
],
|
||||
"ff": [
|
||||
3.5,
|
||||
10,
|
||||
15
|
||||
],
|
||||
"chrome": [
|
||||
10,
|
||||
22
|
||||
],
|
||||
"safari": [
|
||||
5.1
|
||||
],
|
||||
"opera": [
|
||||
12
|
||||
]
|
||||
}
|
||||
},
|
||||
"version": "0.0.1"
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
var concatMap = require('../');
|
||||
var test = require('tape');
|
||||
|
||||
test('empty or not', function (t) {
|
||||
var xs = [ 1, 2, 3, 4, 5, 6 ];
|
||||
var ixes = [];
|
||||
var ys = concatMap(xs, function (x, ix) {
|
||||
ixes.push(ix);
|
||||
return x % 2 ? [ x - 0.1, x, x + 0.1 ] : [];
|
||||
});
|
||||
t.same(ys, [ 0.9, 1, 1.1, 2.9, 3, 3.1, 4.9, 5, 5.1 ]);
|
||||
t.same(ixes, [ 0, 1, 2, 3, 4, 5 ]);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('always something', function (t) {
|
||||
var xs = [ 'a', 'b', 'c', 'd' ];
|
||||
var ys = concatMap(xs, function (x) {
|
||||
return x === 'b' ? [ 'B', 'B', 'B' ] : [ x ];
|
||||
});
|
||||
t.same(ys, [ 'a', 'B', 'B', 'B', 'c', 'd' ]);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('scalars', function (t) {
|
||||
var xs = [ 'a', 'b', 'c', 'd' ];
|
||||
var ys = concatMap(xs, function (x) {
|
||||
return x === 'b' ? [ 'B', 'B', 'B' ] : x;
|
||||
});
|
||||
t.same(ys, [ 'a', 'B', 'B', 'B', 'c', 'd' ]);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('undefs', function (t) {
|
||||
var xs = [ 'a', 'b', 'c', 'd' ];
|
||||
var ys = concatMap(xs, function () {});
|
||||
t.same(ys, [ undefined, undefined, undefined, undefined ]);
|
||||
t.end();
|
||||
});
|
@ -0,0 +1,43 @@
|
||||
The ISC License
|
||||
|
||||
Copyright (c) Isaac Z. Schlueter and Contributors
|
||||
|
||||
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.
|
||||
|
||||
----
|
||||
|
||||
This library bundles a version of the `fs.realpath` and `fs.realpathSync`
|
||||
methods from Node.js v0.10 under the terms of the Node.js MIT license.
|
||||
|
||||
Node's license follows, also included at the header of `old.js` which contains
|
||||
the licensed code:
|
||||
|
||||
Copyright Joyent, Inc. and other Node contributors.
|
||||
|
||||
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.
|
@ -0,0 +1,33 @@
|
||||
# fs.realpath
|
||||
|
||||
A backwards-compatible fs.realpath for Node v6 and above
|
||||
|
||||
In Node v6, the JavaScript implementation of fs.realpath was replaced
|
||||
with a faster (but less resilient) native implementation. That raises
|
||||
new and platform-specific errors and cannot handle long or excessively
|
||||
symlink-looping paths.
|
||||
|
||||
This module handles those cases by detecting the new errors and
|
||||
falling back to the JavaScript implementation. On versions of Node
|
||||
prior to v6, it has no effect.
|
||||
|
||||
## USAGE
|
||||
|
||||
```js
|
||||
var rp = require('fs.realpath')
|
||||
|
||||
// async version
|
||||
rp.realpath(someLongAndLoopingPath, function (er, real) {
|
||||
// the ELOOP was handled, but it was a bit slower
|
||||
})
|
||||
|
||||
// sync version
|
||||
var real = rp.realpathSync(someLongAndLoopingPath)
|
||||
|
||||
// monkeypatch at your own risk!
|
||||
// This replaces the fs.realpath/fs.realpathSync builtins
|
||||
rp.monkeypatch()
|
||||
|
||||
// un-do the monkeypatching
|
||||
rp.unmonkeypatch()
|
||||
```
|
@ -0,0 +1,66 @@
|
||||
module.exports = realpath
|
||||
realpath.realpath = realpath
|
||||
realpath.sync = realpathSync
|
||||
realpath.realpathSync = realpathSync
|
||||
realpath.monkeypatch = monkeypatch
|
||||
realpath.unmonkeypatch = unmonkeypatch
|
||||
|
||||
var fs = require('fs')
|
||||
var origRealpath = fs.realpath
|
||||
var origRealpathSync = fs.realpathSync
|
||||
|
||||
var version = process.version
|
||||
var ok = /^v[0-5]\./.test(version)
|
||||
var old = require('./old.js')
|
||||
|
||||
function newError (er) {
|
||||
return er && er.syscall === 'realpath' && (
|
||||
er.code === 'ELOOP' ||
|
||||
er.code === 'ENOMEM' ||
|
||||
er.code === 'ENAMETOOLONG'
|
||||
)
|
||||
}
|
||||
|
||||
function realpath (p, cache, cb) {
|
||||
if (ok) {
|
||||
return origRealpath(p, cache, cb)
|
||||
}
|
||||
|
||||
if (typeof cache === 'function') {
|
||||
cb = cache
|
||||
cache = null
|
||||
}
|
||||
origRealpath(p, cache, function (er, result) {
|
||||
if (newError(er)) {
|
||||
old.realpath(p, cache, cb)
|
||||
} else {
|
||||
cb(er, result)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function realpathSync (p, cache) {
|
||||
if (ok) {
|
||||
return origRealpathSync(p, cache)
|
||||
}
|
||||
|
||||
try {
|
||||
return origRealpathSync(p, cache)
|
||||
} catch (er) {
|
||||
if (newError(er)) {
|
||||
return old.realpathSync(p, cache)
|
||||
} else {
|
||||
throw er
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function monkeypatch () {
|
||||
fs.realpath = realpath
|
||||
fs.realpathSync = realpathSync
|
||||
}
|
||||
|
||||
function unmonkeypatch () {
|
||||
fs.realpath = origRealpath
|
||||
fs.realpathSync = origRealpathSync
|
||||
}
|
@ -0,0 +1,303 @@
|
||||
// Copyright Joyent, Inc. and other Node contributors.
|
||||
//
|
||||
// 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.
|
||||
|
||||
var pathModule = require('path');
|
||||
var isWindows = process.platform === 'win32';
|
||||
var fs = require('fs');
|
||||
|
||||
// JavaScript implementation of realpath, ported from node pre-v6
|
||||
|
||||
var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
|
||||
|
||||
function rethrow() {
|
||||
// Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
|
||||
// is fairly slow to generate.
|
||||
var callback;
|
||||
if (DEBUG) {
|
||||
var backtrace = new Error;
|
||||
callback = debugCallback;
|
||||
} else
|
||||
callback = missingCallback;
|
||||
|
||||
return callback;
|
||||
|
||||
function debugCallback(err) {
|
||||
if (err) {
|
||||
backtrace.message = err.message;
|
||||
err = backtrace;
|
||||
missingCallback(err);
|
||||
}
|
||||
}
|
||||
|
||||
function missingCallback(err) {
|
||||
if (err) {
|
||||
if (process.throwDeprecation)
|
||||
throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
|
||||
else if (!process.noDeprecation) {
|
||||
var msg = 'fs: missing callback ' + (err.stack || err.message);
|
||||
if (process.traceDeprecation)
|
||||
console.trace(msg);
|
||||
else
|
||||
console.error(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function maybeCallback(cb) {
|
||||
return typeof cb === 'function' ? cb : rethrow();
|
||||
}
|
||||
|
||||
var normalize = pathModule.normalize;
|
||||
|
||||
// Regexp that finds the next partion of a (partial) path
|
||||
// result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
|
||||
if (isWindows) {
|
||||
var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
|
||||
} else {
|
||||
var nextPartRe = /(.*?)(?:[\/]+|$)/g;
|
||||
}
|
||||
|
||||
// Regex to find the device root, including trailing slash. E.g. 'c:\\'.
|
||||
if (isWindows) {
|
||||
var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
|
||||
} else {
|
||||
var splitRootRe = /^[\/]*/;
|
||||
}
|
||||
|
||||
exports.realpathSync = function realpathSync(p, cache) {
|
||||
// make p is absolute
|
||||
p = pathModule.resolve(p);
|
||||
|
||||
if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
|
||||
return cache[p];
|
||||
}
|
||||
|
||||
var original = p,
|
||||
seenLinks = {},
|
||||
knownHard = {};
|
||||
|
||||
// current character position in p
|
||||
var pos;
|
||||
// the partial path so far, including a trailing slash if any
|
||||
var current;
|
||||
// the partial path without a trailing slash (except when pointing at a root)
|
||||
var base;
|
||||
// the partial path scanned in the previous round, with slash
|
||||
var previous;
|
||||
|
||||
start();
|
||||
|
||||
function start() {
|
||||
// Skip over roots
|
||||
var m = splitRootRe.exec(p);
|
||||
pos = m[0].length;
|
||||
current = m[0];
|
||||
base = m[0];
|
||||
previous = '';
|
||||
|
||||
// On windows, check that the root exists. On unix there is no need.
|
||||
if (isWindows && !knownHard[base]) {
|
||||
fs.lstatSync(base);
|
||||
knownHard[base] = true;
|
||||
}
|
||||
}
|
||||
|
||||
// walk down the path, swapping out linked pathparts for their real
|
||||
// values
|
||||
// NB: p.length changes.
|
||||
while (pos < p.length) {
|
||||
// find the next part
|
||||
nextPartRe.lastIndex = pos;
|
||||
var result = nextPartRe.exec(p);
|
||||
previous = current;
|
||||
current += result[0];
|
||||
base = previous + result[1];
|
||||
pos = nextPartRe.lastIndex;
|
||||
|
||||
// continue if not a symlink
|
||||
if (knownHard[base] || (cache && cache[base] === base)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
var resolvedLink;
|
||||
if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
|
||||
// some known symbolic link. no need to stat again.
|
||||
resolvedLink = cache[base];
|
||||
} else {
|
||||
var stat = fs.lstatSync(base);
|
||||
if (!stat.isSymbolicLink()) {
|
||||
knownHard[base] = true;
|
||||
if (cache) cache[base] = base;
|
||||
continue;
|
||||
}
|
||||
|
||||
// read the link if it wasn't read before
|
||||
// dev/ino always return 0 on windows, so skip the check.
|
||||
var linkTarget = null;
|
||||
if (!isWindows) {
|
||||
var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
|
||||
if (seenLinks.hasOwnProperty(id)) {
|
||||
linkTarget = seenLinks[id];
|
||||
}
|
||||
}
|
||||
if (linkTarget === null) {
|
||||
fs.statSync(base);
|
||||
linkTarget = fs.readlinkSync(base);
|
||||
}
|
||||
resolvedLink = pathModule.resolve(previous, linkTarget);
|
||||
// track this, if given a cache.
|
||||
if (cache) cache[base] = resolvedLink;
|
||||
if (!isWindows) seenLinks[id] = linkTarget;
|
||||
}
|
||||
|
||||
// resolve the link, then start over
|
||||
p = pathModule.resolve(resolvedLink, p.slice(pos));
|
||||
start();
|
||||
}
|
||||
|
||||
if (cache) cache[original] = p;
|
||||
|
||||
return p;
|
||||
};
|
||||
|
||||
|
||||
exports.realpath = function realpath(p, cache, cb) {
|
||||
if (typeof cb !== 'function') {
|
||||
cb = maybeCallback(cache);
|
||||
cache = null;
|
||||
}
|
||||
|
||||
// make p is absolute
|
||||
p = pathModule.resolve(p);
|
||||
|
||||
if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
|
||||
return process.nextTick(cb.bind(null, null, cache[p]));
|
||||
}
|
||||
|
||||
var original = p,
|
||||
seenLinks = {},
|
||||
knownHard = {};
|
||||
|
||||
// current character position in p
|
||||
var pos;
|
||||
// the partial path so far, including a trailing slash if any
|
||||
var current;
|
||||
// the partial path without a trailing slash (except when pointing at a root)
|
||||
var base;
|
||||
// the partial path scanned in the previous round, with slash
|
||||
var previous;
|
||||
|
||||
start();
|
||||
|
||||
function start() {
|
||||
// Skip over roots
|
||||
var m = splitRootRe.exec(p);
|
||||
pos = m[0].length;
|
||||
current = m[0];
|
||||
base = m[0];
|
||||
previous = '';
|
||||
|
||||
// On windows, check that the root exists. On unix there is no need.
|
||||
if (isWindows && !knownHard[base]) {
|
||||
fs.lstat(base, function(err) {
|
||||
if (err) return cb(err);
|
||||
knownHard[base] = true;
|
||||
LOOP();
|
||||
});
|
||||
} else {
|
||||
process.nextTick(LOOP);
|
||||
}
|
||||
}
|
||||
|
||||
// walk down the path, swapping out linked pathparts for their real
|
||||
// values
|
||||
function LOOP() {
|
||||
// stop if scanned past end of path
|
||||
if (pos >= p.length) {
|
||||
if (cache) cache[original] = p;
|
||||
return cb(null, p);
|
||||
}
|
||||
|
||||
// find the next part
|
||||
nextPartRe.lastIndex = pos;
|
||||
var result = nextPartRe.exec(p);
|
||||
previous = current;
|
||||
current += result[0];
|
||||
base = previous + result[1];
|
||||
pos = nextPartRe.lastIndex;
|
||||
|
||||
// continue if not a symlink
|
||||
if (knownHard[base] || (cache && cache[base] === base)) {
|
||||
return process.nextTick(LOOP);
|
||||
}
|
||||
|
||||
if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
|
||||
// known symbolic link. no need to stat again.
|
||||
return gotResolvedLink(cache[base]);
|
||||
}
|
||||
|
||||
return fs.lstat(base, gotStat);
|
||||
}
|
||||
|
||||
function gotStat(err, stat) {
|
||||
if (err) return cb(err);
|
||||
|
||||
// if not a symlink, skip to the next path part
|
||||
if (!stat.isSymbolicLink()) {
|
||||
knownHard[base] = true;
|
||||
if (cache) cache[base] = base;
|
||||
return process.nextTick(LOOP);
|
||||
}
|
||||
|
||||
// stat & read the link if not read before
|
||||
// call gotTarget as soon as the link target is known
|
||||
// dev/ino always return 0 on windows, so skip the check.
|
||||
if (!isWindows) {
|
||||
var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
|
||||
if (seenLinks.hasOwnProperty(id)) {
|
||||
return gotTarget(null, seenLinks[id], base);
|
||||
}
|
||||
}
|
||||
fs.stat(base, function(err) {
|
||||
if (err) return cb(err);
|
||||
|
||||
fs.readlink(base, function(err, target) {
|
||||
if (!isWindows) seenLinks[id] = target;
|
||||
gotTarget(err, target);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function gotTarget(err, target, base) {
|
||||
if (err) return cb(err);
|
||||
|
||||
var resolvedLink = pathModule.resolve(previous, target);
|
||||
if (cache) cache[base] = resolvedLink;
|
||||
gotResolvedLink(resolvedLink);
|
||||
}
|
||||
|
||||
function gotResolvedLink(resolvedLink) {
|
||||
// resolve the link, then start over
|
||||
p = pathModule.resolve(resolvedLink, p.slice(pos));
|
||||
start();
|
||||
}
|
||||
};
|
@ -0,0 +1,59 @@
|
||||
{
|
||||
"_from": "fs.realpath@^1.0.0",
|
||||
"_id": "fs.realpath@1.0.0",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=",
|
||||
"_location": "/fs.realpath",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "fs.realpath@^1.0.0",
|
||||
"name": "fs.realpath",
|
||||
"escapedName": "fs.realpath",
|
||||
"rawSpec": "^1.0.0",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "^1.0.0"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/glob"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
|
||||
"_shasum": "1504ad2523158caa40db4a2787cb01411994ea4f",
|
||||
"_spec": "fs.realpath@^1.0.0",
|
||||
"_where": "/Users/paolo/Desktop/multiplayer games/likelike-online/node_modules/glob",
|
||||
"author": {
|
||||
"name": "Isaac Z. Schlueter",
|
||||
"email": "i@izs.me",
|
||||
"url": "http://blog.izs.me/"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/isaacs/fs.realpath/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"dependencies": {},
|
||||
"deprecated": false,
|
||||
"description": "Use node's fs.realpath, but fall back to the JS implementation if the native one fails",
|
||||
"devDependencies": {},
|
||||
"files": [
|
||||
"old.js",
|
||||
"index.js"
|
||||
],
|
||||
"homepage": "https://github.com/isaacs/fs.realpath#readme",
|
||||
"keywords": [
|
||||
"realpath",
|
||||
"fs",
|
||||
"polyfill"
|
||||
],
|
||||
"license": "ISC",
|
||||
"main": "index.js",
|
||||
"name": "fs.realpath",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/isaacs/fs.realpath.git"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "tap test/*.js --cov"
|
||||
},
|
||||
"version": "1.0.0"
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
The ISC License
|
||||
|
||||
Copyright (c) Isaac Z. Schlueter and Contributors
|
||||
|
||||
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.
|
||||
|
||||
## Glob Logo
|
||||
|
||||
Glob's logo created by Tanya Brassie <http://tanyabrassie.com/>, licensed
|
||||
under a Creative Commons Attribution-ShareAlike 4.0 International License
|
||||
https://creativecommons.org/licenses/by-sa/4.0/
|
@ -0,0 +1,375 @@
|
||||
# Glob
|
||||
|
||||
Match files using the patterns the shell uses, like stars and stuff.
|
||||
|
||||
[![Build Status](https://travis-ci.org/isaacs/node-glob.svg?branch=master)](https://travis-ci.org/isaacs/node-glob/) [![Build Status](https://ci.appveyor.com/api/projects/status/kd7f3yftf7unxlsx?svg=true)](https://ci.appveyor.com/project/isaacs/node-glob) [![Coverage Status](https://coveralls.io/repos/isaacs/node-glob/badge.svg?branch=master&service=github)](https://coveralls.io/github/isaacs/node-glob?branch=master)
|
||||
|
||||
This is a glob implementation in JavaScript. It uses the `minimatch`
|
||||
library to do its matching.
|
||||
|
||||
![](logo/glob.png)
|
||||
|
||||
## Usage
|
||||
|
||||
Install with npm
|
||||
|
||||
```
|
||||
npm i glob
|
||||
```
|
||||
|
||||
```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.
|
||||
})
|
||||
```
|
||||
|
||||
## Glob Primer
|
||||
|
||||
"Globs" are the patterns you type when you do stuff like `ls *.js` on
|
||||
the command line, or put `build/*` in a `.gitignore` file.
|
||||
|
||||
Before parsing the path part patterns, braced sections are expanded
|
||||
into a set. Braced sections start with `{` and end with `}`, with any
|
||||
number of comma-delimited sections within. Braced sections may contain
|
||||
slash characters, so `a{/b/c,bcd}` would expand into `a/b/c` and `abcd`.
|
||||
|
||||
The following characters have special magic meaning when used in a
|
||||
path portion:
|
||||
|
||||
* `*` Matches 0 or more characters in a single path portion
|
||||
* `?` Matches 1 character
|
||||
* `[...]` Matches a range of characters, similar to a RegExp range.
|
||||
If the first character of the range is `!` or `^` then it matches
|
||||
any character not in the range.
|
||||
* `!(pattern|pattern|pattern)` Matches anything that does not match
|
||||
any of the patterns provided.
|
||||
* `?(pattern|pattern|pattern)` Matches zero or one occurrence of the
|
||||
patterns provided.
|
||||
* `+(pattern|pattern|pattern)` Matches one or more occurrences of the
|
||||
patterns provided.
|
||||
* `*(a|b|c)` Matches zero or more occurrences of the patterns provided
|
||||
* `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns
|
||||
provided
|
||||
* `**` If a "globstar" is alone in a path portion, then it matches
|
||||
zero or more directories and subdirectories searching for matches.
|
||||
It does not crawl symlinked directories.
|
||||
|
||||
### Dots
|
||||
|
||||
If a file or directory path portion has a `.` as the first character,
|
||||
then it will not match any glob pattern unless that pattern's
|
||||
corresponding path part also has a `.` as its first character.
|
||||
|
||||
For example, the pattern `a/.*/c` would match the file at `a/.b/c`.
|
||||
However the pattern `a/*/c` would not, because `*` does not start with
|
||||
a dot character.
|
||||
|
||||
You can make glob treat dots as normal characters by setting
|
||||
`dot:true` in the options.
|
||||
|
||||
### Basename Matching
|
||||
|
||||
If you set `matchBase:true` in the options, and the pattern has no
|
||||
slashes in it, then it will seek for any file anywhere in the tree
|
||||
with a matching basename. For example, `*.js` would match
|
||||
`test/simple/basic.js`.
|
||||
|
||||
### Empty Sets
|
||||
|
||||
If no matching files are found, then an empty array is returned. This
|
||||
differs from the shell, where the pattern itself is returned. For
|
||||
example:
|
||||
|
||||
$ echo a*s*d*f
|
||||
a*s*d*f
|
||||
|
||||
To get the bash-style behavior, set the `nonull:true` in the options.
|
||||
|
||||
### See Also:
|
||||
|
||||
* `man sh`
|
||||
* `man bash` (Search for "Pattern Matching")
|
||||
* `man 3 fnmatch`
|
||||
* `man 5 gitignore`
|
||||
* [minimatch documentation](https://github.com/isaacs/minimatch)
|
||||
|
||||
## glob.hasMagic(pattern, [options])
|
||||
|
||||
Returns `true` if there are any special characters in the pattern, and
|
||||
`false` otherwise.
|
||||
|
||||
Note that the options affect the results. If `noext:true` is set in
|
||||
the options object, then `+(a|b)` will not be considered a magic
|
||||
pattern. If the pattern has a brace expansion, like `a/{b/c,x/y}`
|
||||
then that is considered magical, unless `nobrace:true` is set in the
|
||||
options.
|
||||
|
||||
## 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 instantiating 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.
|
||||
* `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.
|
||||
* `cache` Convenience object. Each field has the following possible
|
||||
values:
|
||||
* `false` - Path does not exist
|
||||
* `true` - Path exists
|
||||
* `'FILE'` - Path exists, and is not a directory
|
||||
* `'DIR'` - Path exists, and is a directory
|
||||
* `[file, entries, ...]` - Path exists, is a directory, and the
|
||||
array value is the results of `fs.readdir`
|
||||
* `statCache` Cache of `fs.stat` results, to prevent statting the same
|
||||
path multiple times.
|
||||
* `symlinks` A record of which paths are symbolic links, which is
|
||||
relevant in resolving `**` patterns.
|
||||
* `realpathCache` An optional object which is passed to `fs.realpath`
|
||||
to minimize unnecessary syscalls. It is stored on the instantiated
|
||||
Glob object, and may be re-used.
|
||||
|
||||
### 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 specific
|
||||
thing that matched. It is not deduplicated or resolved to a realpath.
|
||||
* `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
|
||||
|
||||
* `pause` Temporarily stop the search
|
||||
* `resume` Resume the search
|
||||
* `abort` Stop the search forever
|
||||
|
||||
### 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.
|
||||
|
||||
If you are running many `glob` operations, you can pass a Glob object
|
||||
as the `options` argument to a subsequent operation to shortcut some
|
||||
`stat` and `readdir` calls. At the very least, you may pass in shared
|
||||
`symlinks`, `statCache`, `realpathCache`, and `cache` options, so that
|
||||
parallel glob operations will be sped up by sharing information about
|
||||
the filesystem.
|
||||
|
||||
* `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.
|
||||
* `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.)
|
||||
* `symlinks` A cache of known symbolic links. You may pass in a
|
||||
previously generated `symlinks` object to save `lstat` calls when
|
||||
resolving `**` matches.
|
||||
* `sync` DEPRECATED: use `glob.sync(pattern, opts)` instead.
|
||||
* `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).
|
||||
* `debug` Set to enable debug logging in minimatch and glob.
|
||||
* `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets.
|
||||
* `noglobstar` Do not match `**` against multiple filenames. (Ie,
|
||||
treat it as a normal `*` instead.)
|
||||
* `noext` Do not match `+(a|b)` "extglob" patterns.
|
||||
* `nocase` Perform a case-insensitive match. Note: on
|
||||
case-insensitive filesystems, non-magic patterns will match by
|
||||
default, since `stat` and `readdir` will not raise errors.
|
||||
* `matchBase` Perform a basename-only match if the pattern does not
|
||||
contain any slash characters. That is, `*.js` would be treated as
|
||||
equivalent to `**/*.js`, matching all js files in all directories.
|
||||
* `nodir` Do not match directories, only files. (Note: to match
|
||||
*only* directories, simply put a `/` at the end of the pattern.)
|
||||
* `ignore` Add a pattern or an array of glob patterns to exclude matches.
|
||||
Note: `ignore` patterns are *always* in `dot:true` mode, regardless
|
||||
of any other settings.
|
||||
* `follow` Follow symlinked directories when expanding `**` patterns.
|
||||
Note that this can result in a lot of duplicate references in the
|
||||
presence of cyclic links.
|
||||
* `realpath` Set to true to call `fs.realpath` on all of the results.
|
||||
In the case of a symlink that cannot be resolved, the full absolute
|
||||
path to the matched entry is returned (though it will usually be a
|
||||
broken symlink)
|
||||
* `absolute` Set to true to always receive absolute paths for matched
|
||||
files. Unlike `realpath`, this also affects the values returned in
|
||||
the `match` event.
|
||||
|
||||
## 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.
|
||||
|
||||
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.3, 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.
|
||||
|
||||
Note that symlinked directories are not crawled as part of a `**`,
|
||||
though their contents may match against subsequent portions of the
|
||||
pattern. This prevents infinite loops and duplicates and the like.
|
||||
|
||||
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.
|
||||
|
||||
### Comments and Negation
|
||||
|
||||
Previously, this module let you mark a pattern as a "comment" if it
|
||||
started with a `#` character, or a "negated" pattern if it started
|
||||
with a `!` character.
|
||||
|
||||
These options were deprecated in version 5, and removed in version 6.
|
||||
|
||||
To specify things that should not match, use the `ignore` option.
|
||||
|
||||
## 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.
|
||||
|
||||
## Glob Logo
|
||||
Glob's logo was created by [Tanya Brassie](http://tanyabrassie.com/). Logo files can be found [here](https://github.com/isaacs/node-glob/tree/master/logo).
|
||||
|
||||
The logo is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/).
|
||||
|
||||
## Contributing
|
||||
|
||||
Any change to behavior (including bugfixes) must come with a test.
|
||||
|
||||
Patches that fail tests or reduce performance will be rejected.
|
||||
|
||||
```
|
||||
# to run tests
|
||||
npm test
|
||||
|
||||
# to re-generate test fixtures
|
||||
npm run test-regen
|
||||
|
||||
# to benchmark against bash/zsh
|
||||
npm run bench
|
||||
|
||||
# to profile javascript
|
||||
npm run prof
|
||||
```
|
||||
|
||||
![](oh-my-glob.gif)
|
@ -0,0 +1,67 @@
|
||||
## 7.0
|
||||
|
||||
- Raise error if `options.cwd` is specified, and not a directory
|
||||
|
||||
## 6.0
|
||||
|
||||
- Remove comment and negation pattern support
|
||||
- Ignore patterns are always in `dot:true` mode
|
||||
|
||||
## 5.0
|
||||
|
||||
- Deprecate comment and negation patterns
|
||||
- Fix regression in `mark` and `nodir` options from making all cache
|
||||
keys absolute path.
|
||||
- Abort if `fs.readdir` returns an error that's unexpected
|
||||
- Don't emit `match` events for ignored items
|
||||
- Treat ENOTSUP like ENOTDIR in readdir
|
||||
|
||||
## 4.5
|
||||
|
||||
- Add `options.follow` to always follow directory symlinks in globstar
|
||||
- Add `options.realpath` to call `fs.realpath` on all results
|
||||
- Always cache based on absolute path
|
||||
|
||||
## 4.4
|
||||
|
||||
- Add `options.ignore`
|
||||
- Fix handling of broken symlinks
|
||||
|
||||
## 4.3
|
||||
|
||||
- Bump minimatch to 2.x
|
||||
- Pass all tests on Windows
|
||||
|
||||
## 4.2
|
||||
|
||||
- Add `glob.hasMagic` function
|
||||
- Add `options.nodir` flag
|
||||
|
||||
## 4.1
|
||||
|
||||
- Refactor sync and async implementations for performance
|
||||
- Throw if callback provided to sync glob function
|
||||
- Treat symbolic links in globstar results the same as Bash 4.3
|
||||
|
||||
## 4.0
|
||||
|
||||
- Use `^` for dependency versions (bumped major because this breaks
|
||||
older npm versions)
|
||||
- Ensure callbacks are only ever called once
|
||||
- switch to ISC license
|
||||
|
||||
## 3.x
|
||||
|
||||
- Rewrite in JavaScript
|
||||
- Add support for setting root, cwd, and windows support
|
||||
- Cache many fs calls
|
||||
- Add globstar support
|
||||
- emit match events
|
||||
|
||||
## 2.x
|
||||
|
||||
- Use `glob.h` and `fnmatch.h` from NetBSD
|
||||
|
||||
## 1.x
|
||||
|
||||
- `glob.h` static binding.
|
@ -0,0 +1,240 @@
|
||||
exports.alphasort = alphasort
|
||||
exports.alphasorti = alphasorti
|
||||
exports.setopts = setopts
|
||||
exports.ownProp = ownProp
|
||||
exports.makeAbs = makeAbs
|
||||
exports.finish = finish
|
||||
exports.mark = mark
|
||||
exports.isIgnored = isIgnored
|
||||
exports.childrenIgnored = childrenIgnored
|
||||
|
||||
function ownProp (obj, field) {
|
||||
return Object.prototype.hasOwnProperty.call(obj, field)
|
||||
}
|
||||
|
||||
var path = require("path")
|
||||
var minimatch = require("minimatch")
|
||||
var isAbsolute = require("path-is-absolute")
|
||||
var Minimatch = minimatch.Minimatch
|
||||
|
||||
function alphasorti (a, b) {
|
||||
return a.toLowerCase().localeCompare(b.toLowerCase())
|
||||
}
|
||||
|
||||
function alphasort (a, b) {
|
||||
return a.localeCompare(b)
|
||||
}
|
||||
|
||||
function setupIgnores (self, options) {
|
||||
self.ignore = options.ignore || []
|
||||
|
||||
if (!Array.isArray(self.ignore))
|
||||
self.ignore = [self.ignore]
|
||||
|
||||
if (self.ignore.length) {
|
||||
self.ignore = self.ignore.map(ignoreMap)
|
||||
}
|
||||
}
|
||||
|
||||
// ignore patterns are always in dot:true mode.
|
||||
function ignoreMap (pattern) {
|
||||
var gmatcher = null
|
||||
if (pattern.slice(-3) === '/**') {
|
||||
var gpattern = pattern.replace(/(\/\*\*)+$/, '')
|
||||
gmatcher = new Minimatch(gpattern, { dot: true })
|
||||
}
|
||||
|
||||
return {
|
||||
matcher: new Minimatch(pattern, { dot: true }),
|
||||
gmatcher: gmatcher
|
||||
}
|
||||
}
|
||||
|
||||
function setopts (self, pattern, options) {
|
||||
if (!options)
|
||||
options = {}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
self.silent = !!options.silent
|
||||
self.pattern = pattern
|
||||
self.strict = options.strict !== false
|
||||
self.realpath = !!options.realpath
|
||||
self.realpathCache = options.realpathCache || Object.create(null)
|
||||
self.follow = !!options.follow
|
||||
self.dot = !!options.dot
|
||||
self.mark = !!options.mark
|
||||
self.nodir = !!options.nodir
|
||||
if (self.nodir)
|
||||
self.mark = true
|
||||
self.sync = !!options.sync
|
||||
self.nounique = !!options.nounique
|
||||
self.nonull = !!options.nonull
|
||||
self.nosort = !!options.nosort
|
||||
self.nocase = !!options.nocase
|
||||
self.stat = !!options.stat
|
||||
self.noprocess = !!options.noprocess
|
||||
self.absolute = !!options.absolute
|
||||
|
||||
self.maxLength = options.maxLength || Infinity
|
||||
self.cache = options.cache || Object.create(null)
|
||||
self.statCache = options.statCache || Object.create(null)
|
||||
self.symlinks = options.symlinks || Object.create(null)
|
||||
|
||||
setupIgnores(self, options)
|
||||
|
||||
self.changedCwd = false
|
||||
var cwd = process.cwd()
|
||||
if (!ownProp(options, "cwd"))
|
||||
self.cwd = cwd
|
||||
else {
|
||||
self.cwd = path.resolve(options.cwd)
|
||||
self.changedCwd = self.cwd !== cwd
|
||||
}
|
||||
|
||||
self.root = options.root || path.resolve(self.cwd, "/")
|
||||
self.root = path.resolve(self.root)
|
||||
if (process.platform === "win32")
|
||||
self.root = self.root.replace(/\\/g, "/")
|
||||
|
||||
// TODO: is an absolute `cwd` supposed to be resolved against `root`?
|
||||
// e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
|
||||
self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd)
|
||||
if (process.platform === "win32")
|
||||
self.cwdAbs = self.cwdAbs.replace(/\\/g, "/")
|
||||
self.nomount = !!options.nomount
|
||||
|
||||
// disable comments and negation in Minimatch.
|
||||
// Note that they are not supported in Glob itself anyway.
|
||||
options.nonegate = true
|
||||
options.nocomment = true
|
||||
|
||||
self.minimatch = new Minimatch(pattern, options)
|
||||
self.options = self.minimatch.options
|
||||
}
|
||||
|
||||
function finish (self) {
|
||||
var nou = self.nounique
|
||||
var all = nou ? [] : Object.create(null)
|
||||
|
||||
for (var i = 0, l = self.matches.length; i < l; i ++) {
|
||||
var matches = self.matches[i]
|
||||
if (!matches || Object.keys(matches).length === 0) {
|
||||
if (self.nonull) {
|
||||
// do like the shell, and spit out the literal glob
|
||||
var literal = self.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 (!self.nosort)
|
||||
all = all.sort(self.nocase ? alphasorti : alphasort)
|
||||
|
||||
// at *some* point we statted all of these
|
||||
if (self.mark) {
|
||||
for (var i = 0; i < all.length; i++) {
|
||||
all[i] = self._mark(all[i])
|
||||
}
|
||||
if (self.nodir) {
|
||||
all = all.filter(function (e) {
|
||||
var notDir = !(/\/$/.test(e))
|
||||
var c = self.cache[e] || self.cache[makeAbs(self, e)]
|
||||
if (notDir && c)
|
||||
notDir = c !== 'DIR' && !Array.isArray(c)
|
||||
return notDir
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (self.ignore.length)
|
||||
all = all.filter(function(m) {
|
||||
return !isIgnored(self, m)
|
||||
})
|
||||
|
||||
self.found = all
|
||||
}
|
||||
|
||||
function mark (self, p) {
|
||||
var abs = makeAbs(self, p)
|
||||
var c = self.cache[abs]
|
||||
var m = p
|
||||
if (c) {
|
||||
var isDir = c === 'DIR' || Array.isArray(c)
|
||||
var slash = p.slice(-1) === '/'
|
||||
|
||||
if (isDir && !slash)
|
||||
m += '/'
|
||||
else if (!isDir && slash)
|
||||
m = m.slice(0, -1)
|
||||
|
||||
if (m !== p) {
|
||||
var mabs = makeAbs(self, m)
|
||||
self.statCache[mabs] = self.statCache[abs]
|
||||
self.cache[mabs] = self.cache[abs]
|
||||
}
|
||||
}
|
||||
|
||||
return m
|
||||
}
|
||||
|
||||
// lotta situps...
|
||||
function makeAbs (self, f) {
|
||||
var abs = f
|
||||
if (f.charAt(0) === '/') {
|
||||
abs = path.join(self.root, f)
|
||||
} else if (isAbsolute(f) || f === '') {
|
||||
abs = f
|
||||
} else if (self.changedCwd) {
|
||||
abs = path.resolve(self.cwd, f)
|
||||
} else {
|
||||
abs = path.resolve(f)
|
||||
}
|
||||
|
||||
if (process.platform === 'win32')
|
||||
abs = abs.replace(/\\/g, '/')
|
||||
|
||||
return abs
|
||||
}
|
||||
|
||||
|
||||
// Return true, if pattern ends with globstar '**', for the accompanying parent directory.
|
||||
// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
|
||||
function isIgnored (self, path) {
|
||||
if (!self.ignore.length)
|
||||
return false
|
||||
|
||||
return self.ignore.some(function(item) {
|
||||
return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))
|
||||
})
|
||||
}
|
||||
|
||||
function childrenIgnored (self, path) {
|
||||
if (!self.ignore.length)
|
||||
return false
|
||||
|
||||
return self.ignore.some(function(item) {
|
||||
return !!(item.gmatcher && item.gmatcher.match(path))
|
||||
})
|
||||
}
|
@ -0,0 +1,790 @@
|
||||
// Approach:
|
||||
//
|
||||
// 1. Get the minimatch set
|
||||
// 2. For each pattern in the set, PROCESS(pattern, false)
|
||||
// 3. Store matches per-set, then uniq them
|
||||
//
|
||||
// PROCESS(pattern, inGlobStar)
|
||||
// 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.
|
||||
//
|
||||
// If inGlobStar and PREFIX is symlink and points to dir
|
||||
// set ENTRIES = []
|
||||
// else readdir(PREFIX) as ENTRIES
|
||||
// If fail, END
|
||||
//
|
||||
// with ENTRIES
|
||||
// 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 .. $], false)
|
||||
// // handle other cases.
|
||||
// for ENTRY in ENTRIES (not dotfiles)
|
||||
// // attach globstar + tail onto the entry
|
||||
// // Mark that this entry is a globstar match
|
||||
// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
|
||||
//
|
||||
// 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('fs')
|
||||
var rp = require('fs.realpath')
|
||||
var minimatch = require('minimatch')
|
||||
var Minimatch = minimatch.Minimatch
|
||||
var inherits = require('inherits')
|
||||
var EE = require('events').EventEmitter
|
||||
var path = require('path')
|
||||
var assert = require('assert')
|
||||
var isAbsolute = require('path-is-absolute')
|
||||
var globSync = require('./sync.js')
|
||||
var common = require('./common.js')
|
||||
var alphasort = common.alphasort
|
||||
var alphasorti = common.alphasorti
|
||||
var setopts = common.setopts
|
||||
var ownProp = common.ownProp
|
||||
var inflight = require('inflight')
|
||||
var util = require('util')
|
||||
var childrenIgnored = common.childrenIgnored
|
||||
var isIgnored = common.isIgnored
|
||||
|
||||
var once = require('once')
|
||||
|
||||
function glob (pattern, options, cb) {
|
||||
if (typeof options === 'function') cb = options, options = {}
|
||||
if (!options) options = {}
|
||||
|
||||
if (options.sync) {
|
||||
if (cb)
|
||||
throw new TypeError('callback provided to sync glob')
|
||||
return globSync(pattern, options)
|
||||
}
|
||||
|
||||
return new Glob(pattern, options, cb)
|
||||
}
|
||||
|
||||
glob.sync = globSync
|
||||
var GlobSync = glob.GlobSync = globSync.GlobSync
|
||||
|
||||
// old api surface
|
||||
glob.glob = glob
|
||||
|
||||
function extend (origin, add) {
|
||||
if (add === null || typeof add !== 'object') {
|
||||
return origin
|
||||
}
|
||||
|
||||
var keys = Object.keys(add)
|
||||
var i = keys.length
|
||||
while (i--) {
|
||||
origin[keys[i]] = add[keys[i]]
|
||||
}
|
||||
return origin
|
||||
}
|
||||
|
||||
glob.hasMagic = function (pattern, options_) {
|
||||
var options = extend({}, options_)
|
||||
options.noprocess = true
|
||||
|
||||
var g = new Glob(pattern, options)
|
||||
var set = g.minimatch.set
|
||||
|
||||
if (!pattern)
|
||||
return false
|
||||
|
||||
if (set.length > 1)
|
||||
return true
|
||||
|
||||
for (var j = 0; j < set[0].length; j++) {
|
||||
if (typeof set[0][j] !== 'string')
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
glob.Glob = Glob
|
||||
inherits(Glob, EE)
|
||||
function Glob (pattern, options, cb) {
|
||||
if (typeof options === 'function') {
|
||||
cb = options
|
||||
options = null
|
||||
}
|
||||
|
||||
if (options && options.sync) {
|
||||
if (cb)
|
||||
throw new TypeError('callback provided to sync glob')
|
||||
return new GlobSync(pattern, options)
|
||||
}
|
||||
|
||||
if (!(this instanceof Glob))
|
||||
return new Glob(pattern, options, cb)
|
||||
|
||||
setopts(this, pattern, options)
|
||||
this._didRealPath = false
|
||||
|
||||
// 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)
|
||||
|
||||
if (typeof cb === 'function') {
|
||||
cb = once(cb)
|
||||
this.on('error', cb)
|
||||
this.on('end', function (matches) {
|
||||
cb(null, matches)
|
||||
})
|
||||
}
|
||||
|
||||
var self = this
|
||||
this._processing = 0
|
||||
|
||||
this._emitQueue = []
|
||||
this._processQueue = []
|
||||
this.paused = false
|
||||
|
||||
if (this.noprocess)
|
||||
return this
|
||||
|
||||
if (n === 0)
|
||||
return done()
|
||||
|
||||
var sync = true
|
||||
for (var i = 0; i < n; i ++) {
|
||||
this._process(this.minimatch.set[i], i, false, done)
|
||||
}
|
||||
sync = false
|
||||
|
||||
function done () {
|
||||
--self._processing
|
||||
if (self._processing <= 0) {
|
||||
if (sync) {
|
||||
process.nextTick(function () {
|
||||
self._finish()
|
||||
})
|
||||
} else {
|
||||
self._finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Glob.prototype._finish = function () {
|
||||
assert(this instanceof Glob)
|
||||
if (this.aborted)
|
||||
return
|
||||
|
||||
if (this.realpath && !this._didRealpath)
|
||||
return this._realpath()
|
||||
|
||||
common.finish(this)
|
||||
this.emit('end', this.found)
|
||||
}
|
||||
|
||||
Glob.prototype._realpath = function () {
|
||||
if (this._didRealpath)
|
||||
return
|
||||
|
||||
this._didRealpath = true
|
||||
|
||||
var n = this.matches.length
|
||||
if (n === 0)
|
||||
return this._finish()
|
||||
|
||||
var self = this
|
||||
for (var i = 0; i < this.matches.length; i++)
|
||||
this._realpathSet(i, next)
|
||||
|
||||
function next () {
|
||||
if (--n === 0)
|
||||
self._finish()
|
||||
}
|
||||
}
|
||||
|
||||
Glob.prototype._realpathSet = function (index, cb) {
|
||||
var matchset = this.matches[index]
|
||||
if (!matchset)
|
||||
return cb()
|
||||
|
||||
var found = Object.keys(matchset)
|
||||
var self = this
|
||||
var n = found.length
|
||||
|
||||
if (n === 0)
|
||||
return cb()
|
||||
|
||||
var set = this.matches[index] = Object.create(null)
|
||||
found.forEach(function (p, i) {
|
||||
// If there's a problem with the stat, then it means that
|
||||
// one or more of the links in the realpath couldn't be
|
||||
// resolved. just return the abs value in that case.
|
||||
p = self._makeAbs(p)
|
||||
rp.realpath(p, self.realpathCache, function (er, real) {
|
||||
if (!er)
|
||||
set[real] = true
|
||||
else if (er.syscall === 'stat')
|
||||
set[p] = true
|
||||
else
|
||||
self.emit('error', er) // srsly wtf right here
|
||||
|
||||
if (--n === 0) {
|
||||
self.matches[index] = set
|
||||
cb()
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
Glob.prototype._mark = function (p) {
|
||||
return common.mark(this, p)
|
||||
}
|
||||
|
||||
Glob.prototype._makeAbs = function (f) {
|
||||
return common.makeAbs(this, f)
|
||||
}
|
||||
|
||||
Glob.prototype.abort = function () {
|
||||
this.aborted = true
|
||||
this.emit('abort')
|
||||
}
|
||||
|
||||
Glob.prototype.pause = function () {
|
||||
if (!this.paused) {
|
||||
this.paused = true
|
||||
this.emit('pause')
|
||||
}
|
||||
}
|
||||
|
||||
Glob.prototype.resume = function () {
|
||||
if (this.paused) {
|
||||
this.emit('resume')
|
||||
this.paused = false
|
||||
if (this._emitQueue.length) {
|
||||
var eq = this._emitQueue.slice(0)
|
||||
this._emitQueue.length = 0
|
||||
for (var i = 0; i < eq.length; i ++) {
|
||||
var e = eq[i]
|
||||
this._emitMatch(e[0], e[1])
|
||||
}
|
||||
}
|
||||
if (this._processQueue.length) {
|
||||
var pq = this._processQueue.slice(0)
|
||||
this._processQueue.length = 0
|
||||
for (var i = 0; i < pq.length; i ++) {
|
||||
var p = pq[i]
|
||||
this._processing--
|
||||
this._process(p[0], p[1], p[2], p[3])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
|
||||
assert(this instanceof Glob)
|
||||
assert(typeof cb === 'function')
|
||||
|
||||
if (this.aborted)
|
||||
return
|
||||
|
||||
this._processing++
|
||||
if (this.paused) {
|
||||
this._processQueue.push([pattern, index, inGlobStar, cb])
|
||||
return
|
||||
}
|
||||
|
||||
//console.error('PROCESS %d', this._processing, pattern)
|
||||
|
||||
// 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:
|
||||
this._processSimple(pattern.join('/'), index, 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).join('/')
|
||||
break
|
||||
}
|
||||
|
||||
var remain = pattern.slice(n)
|
||||
|
||||
// get the list of entries.
|
||||
var read
|
||||
if (prefix === null)
|
||||
read = '.'
|
||||
else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
|
||||
if (!prefix || !isAbsolute(prefix))
|
||||
prefix = '/' + prefix
|
||||
read = prefix
|
||||
} else
|
||||
read = prefix
|
||||
|
||||
var abs = this._makeAbs(read)
|
||||
|
||||
//if ignored, skip _processing
|
||||
if (childrenIgnored(this, read))
|
||||
return cb()
|
||||
|
||||
var isGlobStar = remain[0] === minimatch.GLOBSTAR
|
||||
if (isGlobStar)
|
||||
this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb)
|
||||
else
|
||||
this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb)
|
||||
}
|
||||
|
||||
Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
|
||||
var self = this
|
||||
this._readdir(abs, inGlobStar, function (er, entries) {
|
||||
return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
|
||||
})
|
||||
}
|
||||
|
||||
Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
|
||||
|
||||
// if the abs isn't a dir, then nothing can match!
|
||||
if (!entries)
|
||||
return cb()
|
||||
|
||||
// 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 = remain[0]
|
||||
var negate = !!this.minimatch.negate
|
||||
var rawGlob = pn._glob
|
||||
var dotOk = this.dot || rawGlob.charAt(0) === '.'
|
||||
|
||||
var matchedEntries = []
|
||||
for (var i = 0; i < entries.length; i++) {
|
||||
var e = entries[i]
|
||||
if (e.charAt(0) !== '.' || dotOk) {
|
||||
var m
|
||||
if (negate && !prefix) {
|
||||
m = !e.match(pn)
|
||||
} else {
|
||||
m = e.match(pn)
|
||||
}
|
||||
if (m)
|
||||
matchedEntries.push(e)
|
||||
}
|
||||
}
|
||||
|
||||
//console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
|
||||
|
||||
var len = matchedEntries.length
|
||||
// If there are no matched entries, then nothing matches.
|
||||
if (len === 0)
|
||||
return cb()
|
||||
|
||||
// if this is the last remaining pattern bit, then no need for
|
||||
// an additional stat *unless* the user has specified mark or
|
||||
// stat explicitly. We know they exist, since readdir returned
|
||||
// them.
|
||||
|
||||
if (remain.length === 1 && !this.mark && !this.stat) {
|
||||
if (!this.matches[index])
|
||||
this.matches[index] = Object.create(null)
|
||||
|
||||
for (var i = 0; i < len; i ++) {
|
||||
var e = matchedEntries[i]
|
||||
if (prefix) {
|
||||
if (prefix !== '/')
|
||||
e = prefix + '/' + e
|
||||
else
|
||||
e = prefix + e
|
||||
}
|
||||
|
||||
if (e.charAt(0) === '/' && !this.nomount) {
|
||||
e = path.join(this.root, e)
|
||||
}
|
||||
this._emitMatch(index, e)
|
||||
}
|
||||
// This was the last one, and no stats were needed
|
||||
return cb()
|
||||
}
|
||||
|
||||
// now test all matched entries as stand-ins for that part
|
||||
// of the pattern.
|
||||
remain.shift()
|
||||
for (var i = 0; i < len; i ++) {
|
||||
var e = matchedEntries[i]
|
||||
var newPattern
|
||||
if (prefix) {
|
||||
if (prefix !== '/')
|
||||
e = prefix + '/' + e
|
||||
else
|
||||
e = prefix + e
|
||||
}
|
||||
this._process([e].concat(remain), index, inGlobStar, cb)
|
||||
}
|
||||
cb()
|
||||
}
|
||||
|
||||
Glob.prototype._emitMatch = function (index, e) {
|
||||
if (this.aborted)
|
||||
return
|
||||
|
||||
if (isIgnored(this, e))
|
||||
return
|
||||
|
||||
if (this.paused) {
|
||||
this._emitQueue.push([index, e])
|
||||
return
|
||||
}
|
||||
|
||||
var abs = isAbsolute(e) ? e : this._makeAbs(e)
|
||||
|
||||
if (this.mark)
|
||||
e = this._mark(e)
|
||||
|
||||
if (this.absolute)
|
||||
e = abs
|
||||
|
||||
if (this.matches[index][e])
|
||||
return
|
||||
|
||||
if (this.nodir) {
|
||||
var c = this.cache[abs]
|
||||
if (c === 'DIR' || Array.isArray(c))
|
||||
return
|
||||
}
|
||||
|
||||
this.matches[index][e] = true
|
||||
|
||||
var st = this.statCache[abs]
|
||||
if (st)
|
||||
this.emit('stat', e, st)
|
||||
|
||||
this.emit('match', e)
|
||||
}
|
||||
|
||||
Glob.prototype._readdirInGlobStar = function (abs, cb) {
|
||||
if (this.aborted)
|
||||
return
|
||||
|
||||
// follow all symlinked directories forever
|
||||
// just proceed as if this is a non-globstar situation
|
||||
if (this.follow)
|
||||
return this._readdir(abs, false, cb)
|
||||
|
||||
var lstatkey = 'lstat\0' + abs
|
||||
var self = this
|
||||
var lstatcb = inflight(lstatkey, lstatcb_)
|
||||
|
||||
if (lstatcb)
|
||||
fs.lstat(abs, lstatcb)
|
||||
|
||||
function lstatcb_ (er, lstat) {
|
||||
if (er && er.code === 'ENOENT')
|
||||
return cb()
|
||||
|
||||
var isSym = lstat && lstat.isSymbolicLink()
|
||||
self.symlinks[abs] = isSym
|
||||
|
||||
// If it's not a symlink or a dir, then it's definitely a regular file.
|
||||
// don't bother doing a readdir in that case.
|
||||
if (!isSym && lstat && !lstat.isDirectory()) {
|
||||
self.cache[abs] = 'FILE'
|
||||
cb()
|
||||
} else
|
||||
self._readdir(abs, false, cb)
|
||||
}
|
||||
}
|
||||
|
||||
Glob.prototype._readdir = function (abs, inGlobStar, cb) {
|
||||
if (this.aborted)
|
||||
return
|
||||
|
||||
cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb)
|
||||
if (!cb)
|
||||
return
|
||||
|
||||
//console.error('RD %j %j', +inGlobStar, abs)
|
||||
if (inGlobStar && !ownProp(this.symlinks, abs))
|
||||
return this._readdirInGlobStar(abs, cb)
|
||||
|
||||
if (ownProp(this.cache, abs)) {
|
||||
var c = this.cache[abs]
|
||||
if (!c || c === 'FILE')
|
||||
return cb()
|
||||
|
||||
if (Array.isArray(c))
|
||||
return cb(null, c)
|
||||
}
|
||||
|
||||
var self = this
|
||||
fs.readdir(abs, readdirCb(this, abs, cb))
|
||||
}
|
||||
|
||||
function readdirCb (self, abs, cb) {
|
||||
return function (er, entries) {
|
||||
if (er)
|
||||
self._readdirError(abs, er, cb)
|
||||
else
|
||||
self._readdirEntries(abs, entries, cb)
|
||||
}
|
||||
}
|
||||
|
||||
Glob.prototype._readdirEntries = function (abs, entries, cb) {
|
||||
if (this.aborted)
|
||||
return
|
||||
|
||||
// if we haven't asked to stat everything, then just
|
||||
// assume that everything in there exists, so we can avoid
|
||||
// having to stat it a second time.
|
||||
if (!this.mark && !this.stat) {
|
||||
for (var i = 0; i < entries.length; i ++) {
|
||||
var e = entries[i]
|
||||
if (abs === '/')
|
||||
e = abs + e
|
||||
else
|
||||
e = abs + '/' + e
|
||||
this.cache[e] = true
|
||||
}
|
||||
}
|
||||
|
||||
this.cache[abs] = entries
|
||||
return cb(null, entries)
|
||||
}
|
||||
|
||||
Glob.prototype._readdirError = function (f, er, cb) {
|
||||
if (this.aborted)
|
||||
return
|
||||
|
||||
// handle errors, and cache the information
|
||||
switch (er.code) {
|
||||
case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
|
||||
case 'ENOTDIR': // totally normal. means it *does* exist.
|
||||
var abs = this._makeAbs(f)
|
||||
this.cache[abs] = 'FILE'
|
||||
if (abs === this.cwdAbs) {
|
||||
var error = new Error(er.code + ' invalid cwd ' + this.cwd)
|
||||
error.path = this.cwd
|
||||
error.code = er.code
|
||||
this.emit('error', error)
|
||||
this.abort()
|
||||
}
|
||||
break
|
||||
|
||||
case 'ENOENT': // not terribly unusual
|
||||
case 'ELOOP':
|
||||
case 'ENAMETOOLONG':
|
||||
case 'UNKNOWN':
|
||||
this.cache[this._makeAbs(f)] = false
|
||||
break
|
||||
|
||||
default: // some unusual error. Treat as failure.
|
||||
this.cache[this._makeAbs(f)] = false
|
||||
if (this.strict) {
|
||||
this.emit('error', er)
|
||||
// If the error is handled, then we abort
|
||||
// if not, we threw out of here
|
||||
this.abort()
|
||||
}
|
||||
if (!this.silent)
|
||||
console.error('glob error', er)
|
||||
break
|
||||
}
|
||||
|
||||
return cb()
|
||||
}
|
||||
|
||||
Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
|
||||
var self = this
|
||||
this._readdir(abs, inGlobStar, function (er, entries) {
|
||||
self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
|
||||
//console.error('pgs2', prefix, remain[0], entries)
|
||||
|
||||
// no entries means not a dir, so it can never have matches
|
||||
// foo.txt/** doesn't match foo.txt
|
||||
if (!entries)
|
||||
return cb()
|
||||
|
||||
// test without the globstar, and with every child both below
|
||||
// and replacing the globstar.
|
||||
var remainWithoutGlobStar = remain.slice(1)
|
||||
var gspref = prefix ? [ prefix ] : []
|
||||
var noGlobStar = gspref.concat(remainWithoutGlobStar)
|
||||
|
||||
// the noGlobStar pattern exits the inGlobStar state
|
||||
this._process(noGlobStar, index, false, cb)
|
||||
|
||||
var isSym = this.symlinks[abs]
|
||||
var len = entries.length
|
||||
|
||||
// If it's a symlink, and we're in a globstar, then stop
|
||||
if (isSym && inGlobStar)
|
||||
return cb()
|
||||
|
||||
for (var i = 0; i < len; i++) {
|
||||
var e = entries[i]
|
||||
if (e.charAt(0) === '.' && !this.dot)
|
||||
continue
|
||||
|
||||
// these two cases enter the inGlobStar state
|
||||
var instead = gspref.concat(entries[i], remainWithoutGlobStar)
|
||||
this._process(instead, index, true, cb)
|
||||
|
||||
var below = gspref.concat(entries[i], remain)
|
||||
this._process(below, index, true, cb)
|
||||
}
|
||||
|
||||
cb()
|
||||
}
|
||||
|
||||
Glob.prototype._processSimple = function (prefix, index, cb) {
|
||||
// XXX review this. Shouldn't it be doing the mounting etc
|
||||
// before doing stat? kinda weird?
|
||||
var self = this
|
||||
this._stat(prefix, function (er, exists) {
|
||||
self._processSimple2(prefix, index, er, exists, cb)
|
||||
})
|
||||
}
|
||||
Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
|
||||
|
||||
//console.error('ps2', prefix, exists)
|
||||
|
||||
if (!this.matches[index])
|
||||
this.matches[index] = Object.create(null)
|
||||
|
||||
// If it doesn't exist, then just mark the lack of results
|
||||
if (!exists)
|
||||
return cb()
|
||||
|
||||
if (prefix && isAbsolute(prefix) && !this.nomount) {
|
||||
var trail = /[\/\\]$/.test(prefix)
|
||||
if (prefix.charAt(0) === '/') {
|
||||
prefix = path.join(this.root, prefix)
|
||||
} else {
|
||||
prefix = path.resolve(this.root, prefix)
|
||||
if (trail)
|
||||
prefix += '/'
|
||||
}
|
||||
}
|
||||
|
||||
if (process.platform === 'win32')
|
||||
prefix = prefix.replace(/\\/g, '/')
|
||||
|
||||
// Mark this as a match
|
||||
this._emitMatch(index, prefix)
|
||||
cb()
|
||||
}
|
||||
|
||||
// Returns either 'DIR', 'FILE', or false
|
||||
Glob.prototype._stat = function (f, cb) {
|
||||
var abs = this._makeAbs(f)
|
||||
var needDir = f.slice(-1) === '/'
|
||||
|
||||
if (f.length > this.maxLength)
|
||||
return cb()
|
||||
|
||||
if (!this.stat && ownProp(this.cache, abs)) {
|
||||
var c = this.cache[abs]
|
||||
|
||||
if (Array.isArray(c))
|
||||
c = 'DIR'
|
||||
|
||||
// It exists, but maybe not how we need it
|
||||
if (!needDir || c === 'DIR')
|
||||
return cb(null, c)
|
||||
|
||||
if (needDir && c === 'FILE')
|
||||
return cb()
|
||||
|
||||
// otherwise we have to stat, because maybe c=true
|
||||
// if we know it exists, but not what it is.
|
||||
}
|
||||
|
||||
var exists
|
||||
var stat = this.statCache[abs]
|
||||
if (stat !== undefined) {
|
||||
if (stat === false)
|
||||
return cb(null, stat)
|
||||
else {
|
||||
var type = stat.isDirectory() ? 'DIR' : 'FILE'
|
||||
if (needDir && type === 'FILE')
|
||||
return cb()
|
||||
else
|
||||
return cb(null, type, stat)
|
||||
}
|
||||
}
|
||||
|
||||
var self = this
|
||||
var statcb = inflight('stat\0' + abs, lstatcb_)
|
||||
if (statcb)
|
||||
fs.lstat(abs, statcb)
|
||||
|
||||
function lstatcb_ (er, lstat) {
|
||||
if (lstat && lstat.isSymbolicLink()) {
|
||||
// If it's a symlink, then treat it as the target, unless
|
||||
// the target does not exist, then treat it as a file.
|
||||
return fs.stat(abs, function (er, stat) {
|
||||
if (er)
|
||||
self._stat2(f, abs, null, lstat, cb)
|
||||
else
|
||||
self._stat2(f, abs, er, stat, cb)
|
||||
})
|
||||
} else {
|
||||
self._stat2(f, abs, er, lstat, cb)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
|
||||
if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
|
||||
this.statCache[abs] = false
|
||||
return cb()
|
||||
}
|
||||
|
||||
var needDir = f.slice(-1) === '/'
|
||||
this.statCache[abs] = stat
|
||||
|
||||
if (abs.slice(-1) === '/' && stat && !stat.isDirectory())
|
||||
return cb(null, false, stat)
|
||||
|
||||
var c = true
|
||||
if (stat)
|
||||
c = stat.isDirectory() ? 'DIR' : 'FILE'
|
||||
this.cache[abs] = this.cache[abs] || c
|
||||
|
||||
if (needDir && c === 'FILE')
|
||||
return cb()
|
||||
|
||||
return cb(null, c, stat)
|
||||
}
|
@ -0,0 +1,79 @@
|
||||
{
|
||||
"_from": "glob@^7.0.5",
|
||||
"_id": "glob@7.1.6",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==",
|
||||
"_location": "/glob",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "glob@^7.0.5",
|
||||
"name": "glob",
|
||||
"escapedName": "glob",
|
||||
"rawSpec": "^7.0.5",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "^7.0.5"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/yamljs"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz",
|
||||
"_shasum": "141f33b81a7c2492e125594307480c46679278a6",
|
||||
"_spec": "glob@^7.0.5",
|
||||
"_where": "/Users/paolo/Desktop/multiplayer games/likelike-online/node_modules/yamljs",
|
||||
"author": {
|
||||
"name": "Isaac Z. Schlueter",
|
||||
"email": "i@izs.me",
|
||||
"url": "http://blog.izs.me/"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/isaacs/node-glob/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"dependencies": {
|
||||
"fs.realpath": "^1.0.0",
|
||||
"inflight": "^1.0.4",
|
||||
"inherits": "2",
|
||||
"minimatch": "^3.0.4",
|
||||
"once": "^1.3.0",
|
||||
"path-is-absolute": "^1.0.0"
|
||||
},
|
||||
"deprecated": false,
|
||||
"description": "a little globber",
|
||||
"devDependencies": {
|
||||
"mkdirp": "0",
|
||||
"rimraf": "^2.2.8",
|
||||
"tap": "^12.0.1",
|
||||
"tick": "0.0.6"
|
||||
},
|
||||
"engines": {
|
||||
"node": "*"
|
||||
},
|
||||
"files": [
|
||||
"glob.js",
|
||||
"sync.js",
|
||||
"common.js"
|
||||
],
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
},
|
||||
"homepage": "https://github.com/isaacs/node-glob#readme",
|
||||
"license": "ISC",
|
||||
"main": "glob.js",
|
||||
"name": "glob",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/isaacs/node-glob.git"
|
||||
},
|
||||
"scripts": {
|
||||
"bench": "bash benchmark.sh",
|
||||
"benchclean": "node benchclean.js",
|
||||
"prepublish": "npm run benchclean",
|
||||
"prof": "bash prof.sh && cat profile.txt",
|
||||
"profclean": "rm -f v8.log profile.txt",
|
||||
"test": "tap test/*.js --cov",
|
||||
"test-regen": "npm run profclean && TEST_REGEN=1 node test/00-setup.js"
|
||||
},
|
||||
"version": "7.1.6"
|
||||
}
|
@ -0,0 +1,486 @@
|
||||
module.exports = globSync
|
||||
globSync.GlobSync = GlobSync
|
||||
|
||||
var fs = require('fs')
|
||||
var rp = require('fs.realpath')
|
||||
var minimatch = require('minimatch')
|
||||
var Minimatch = minimatch.Minimatch
|
||||
var Glob = require('./glob.js').Glob
|
||||
var util = require('util')
|
||||
var path = require('path')
|
||||
var assert = require('assert')
|
||||
var isAbsolute = require('path-is-absolute')
|
||||
var common = require('./common.js')
|
||||
var alphasort = common.alphasort
|
||||
var alphasorti = common.alphasorti
|
||||
var setopts = common.setopts
|
||||
var ownProp = common.ownProp
|
||||
var childrenIgnored = common.childrenIgnored
|
||||
var isIgnored = common.isIgnored
|
||||
|
||||
function globSync (pattern, options) {
|
||||
if (typeof options === 'function' || arguments.length === 3)
|
||||
throw new TypeError('callback provided to sync glob\n'+
|
||||
'See: https://github.com/isaacs/node-glob/issues/167')
|
||||
|
||||
return new GlobSync(pattern, options).found
|
||||
}
|
||||
|
||||
function GlobSync (pattern, options) {
|
||||
if (!pattern)
|
||||
throw new Error('must provide pattern')
|
||||
|
||||
if (typeof options === 'function' || arguments.length === 3)
|
||||
throw new TypeError('callback provided to sync glob\n'+
|
||||
'See: https://github.com/isaacs/node-glob/issues/167')
|
||||
|
||||
if (!(this instanceof GlobSync))
|
||||
return new GlobSync(pattern, options)
|
||||
|
||||
setopts(this, pattern, options)
|
||||
|
||||
if (this.noprocess)
|
||||
return this
|
||||
|
||||
var n = this.minimatch.set.length
|
||||
this.matches = new Array(n)
|
||||
for (var i = 0; i < n; i ++) {
|
||||
this._process(this.minimatch.set[i], i, false)
|
||||
}
|
||||
this._finish()
|
||||
}
|
||||
|
||||
GlobSync.prototype._finish = function () {
|
||||
assert(this instanceof GlobSync)
|
||||
if (this.realpath) {
|
||||
var self = this
|
||||
this.matches.forEach(function (matchset, index) {
|
||||
var set = self.matches[index] = Object.create(null)
|
||||
for (var p in matchset) {
|
||||
try {
|
||||
p = self._makeAbs(p)
|
||||
var real = rp.realpathSync(p, self.realpathCache)
|
||||
set[real] = true
|
||||
} catch (er) {
|
||||
if (er.syscall === 'stat')
|
||||
set[self._makeAbs(p)] = true
|
||||
else
|
||||
throw er
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
common.finish(this)
|
||||
}
|
||||
|
||||
|
||||
GlobSync.prototype._process = function (pattern, index, inGlobStar) {
|
||||
assert(this instanceof GlobSync)
|
||||
|
||||
// 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:
|
||||
this._processSimple(pattern.join('/'), index)
|
||||
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).join('/')
|
||||
break
|
||||
}
|
||||
|
||||
var remain = pattern.slice(n)
|
||||
|
||||
// get the list of entries.
|
||||
var read
|
||||
if (prefix === null)
|
||||
read = '.'
|
||||
else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
|
||||
if (!prefix || !isAbsolute(prefix))
|
||||
prefix = '/' + prefix
|
||||
read = prefix
|
||||
} else
|
||||
read = prefix
|
||||
|
||||
var abs = this._makeAbs(read)
|
||||
|
||||
//if ignored, skip processing
|
||||
if (childrenIgnored(this, read))
|
||||
return
|
||||
|
||||
var isGlobStar = remain[0] === minimatch.GLOBSTAR
|
||||
if (isGlobStar)
|
||||
this._processGlobStar(prefix, read, abs, remain, index, inGlobStar)
|
||||
else
|
||||
this._processReaddir(prefix, read, abs, remain, index, inGlobStar)
|
||||
}
|
||||
|
||||
|
||||
GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
|
||||
var entries = this._readdir(abs, inGlobStar)
|
||||
|
||||
// if the abs isn't a dir, then nothing can match!
|
||||
if (!entries)
|
||||
return
|
||||
|
||||
// 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 = remain[0]
|
||||
var negate = !!this.minimatch.negate
|
||||
var rawGlob = pn._glob
|
||||
var dotOk = this.dot || rawGlob.charAt(0) === '.'
|
||||
|
||||
var matchedEntries = []
|
||||
for (var i = 0; i < entries.length; i++) {
|
||||
var e = entries[i]
|
||||
if (e.charAt(0) !== '.' || dotOk) {
|
||||
var m
|
||||
if (negate && !prefix) {
|
||||
m = !e.match(pn)
|
||||
} else {
|
||||
m = e.match(pn)
|
||||
}
|
||||
if (m)
|
||||
matchedEntries.push(e)
|
||||
}
|
||||
}
|
||||
|
||||
var len = matchedEntries.length
|
||||
// If there are no matched entries, then nothing matches.
|
||||
if (len === 0)
|
||||
return
|
||||
|
||||
// if this is the last remaining pattern bit, then no need for
|
||||
// an additional stat *unless* the user has specified mark or
|
||||
// stat explicitly. We know they exist, since readdir returned
|
||||
// them.
|
||||
|
||||
if (remain.length === 1 && !this.mark && !this.stat) {
|
||||
if (!this.matches[index])
|
||||
this.matches[index] = Object.create(null)
|
||||
|
||||
for (var i = 0; i < len; i ++) {
|
||||
var e = matchedEntries[i]
|
||||
if (prefix) {
|
||||
if (prefix.slice(-1) !== '/')
|
||||
e = prefix + '/' + e
|
||||
else
|
||||
e = prefix + e
|
||||
}
|
||||
|
||||
if (e.charAt(0) === '/' && !this.nomount) {
|
||||
e = path.join(this.root, e)
|
||||
}
|
||||
this._emitMatch(index, e)
|
||||
}
|
||||
// This was the last one, and no stats were needed
|
||||
return
|
||||
}
|
||||
|
||||
// now test all matched entries as stand-ins for that part
|
||||
// of the pattern.
|
||||
remain.shift()
|
||||
for (var i = 0; i < len; i ++) {
|
||||
var e = matchedEntries[i]
|
||||
var newPattern
|
||||
if (prefix)
|
||||
newPattern = [prefix, e]
|
||||
else
|
||||
newPattern = [e]
|
||||
this._process(newPattern.concat(remain), index, inGlobStar)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
GlobSync.prototype._emitMatch = function (index, e) {
|
||||
if (isIgnored(this, e))
|
||||
return
|
||||
|
||||
var abs = this._makeAbs(e)
|
||||
|
||||
if (this.mark)
|
||||
e = this._mark(e)
|
||||
|
||||
if (this.absolute) {
|
||||
e = abs
|
||||
}
|
||||
|
||||
if (this.matches[index][e])
|
||||
return
|
||||
|
||||
if (this.nodir) {
|
||||
var c = this.cache[abs]
|
||||
if (c === 'DIR' || Array.isArray(c))
|
||||
return
|
||||
}
|
||||
|
||||
this.matches[index][e] = true
|
||||
|
||||
if (this.stat)
|
||||
this._stat(e)
|
||||
}
|
||||
|
||||
|
||||
GlobSync.prototype._readdirInGlobStar = function (abs) {
|
||||
// follow all symlinked directories forever
|
||||
// just proceed as if this is a non-globstar situation
|
||||
if (this.follow)
|
||||
return this._readdir(abs, false)
|
||||
|
||||
var entries
|
||||
var lstat
|
||||
var stat
|
||||
try {
|
||||
lstat = fs.lstatSync(abs)
|
||||
} catch (er) {
|
||||
if (er.code === 'ENOENT') {
|
||||
// lstat failed, doesn't exist
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
var isSym = lstat && lstat.isSymbolicLink()
|
||||
this.symlinks[abs] = isSym
|
||||
|
||||
// If it's not a symlink or a dir, then it's definitely a regular file.
|
||||
// don't bother doing a readdir in that case.
|
||||
if (!isSym && lstat && !lstat.isDirectory())
|
||||
this.cache[abs] = 'FILE'
|
||||
else
|
||||
entries = this._readdir(abs, false)
|
||||
|
||||
return entries
|
||||
}
|
||||
|
||||
GlobSync.prototype._readdir = function (abs, inGlobStar) {
|
||||
var entries
|
||||
|
||||
if (inGlobStar && !ownProp(this.symlinks, abs))
|
||||
return this._readdirInGlobStar(abs)
|
||||
|
||||
if (ownProp(this.cache, abs)) {
|
||||
var c = this.cache[abs]
|
||||
if (!c || c === 'FILE')
|
||||
return null
|
||||
|
||||
if (Array.isArray(c))
|
||||
return c
|
||||
}
|
||||
|
||||
try {
|
||||
return this._readdirEntries(abs, fs.readdirSync(abs))
|
||||
} catch (er) {
|
||||
this._readdirError(abs, er)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
GlobSync.prototype._readdirEntries = function (abs, entries) {
|
||||
// if we haven't asked to stat everything, then just
|
||||
// assume that everything in there exists, so we can avoid
|
||||
// having to stat it a second time.
|
||||
if (!this.mark && !this.stat) {
|
||||
for (var i = 0; i < entries.length; i ++) {
|
||||
var e = entries[i]
|
||||
if (abs === '/')
|
||||
e = abs + e
|
||||
else
|
||||
e = abs + '/' + e
|
||||
this.cache[e] = true
|
||||
}
|
||||
}
|
||||
|
||||
this.cache[abs] = entries
|
||||
|
||||
// mark and cache dir-ness
|
||||
return entries
|
||||
}
|
||||
|
||||
GlobSync.prototype._readdirError = function (f, er) {
|
||||
// handle errors, and cache the information
|
||||
switch (er.code) {
|
||||
case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
|
||||
case 'ENOTDIR': // totally normal. means it *does* exist.
|
||||
var abs = this._makeAbs(f)
|
||||
this.cache[abs] = 'FILE'
|
||||
if (abs === this.cwdAbs) {
|
||||
var error = new Error(er.code + ' invalid cwd ' + this.cwd)
|
||||
error.path = this.cwd
|
||||
error.code = er.code
|
||||
throw error
|
||||
}
|
||||
break
|
||||
|
||||
case 'ENOENT': // not terribly unusual
|
||||
case 'ELOOP':
|
||||
case 'ENAMETOOLONG':
|
||||
case 'UNKNOWN':
|
||||
this.cache[this._makeAbs(f)] = false
|
||||
break
|
||||
|
||||
default: // some unusual error. Treat as failure.
|
||||
this.cache[this._makeAbs(f)] = false
|
||||
if (this.strict)
|
||||
throw er
|
||||
if (!this.silent)
|
||||
console.error('glob error', er)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
|
||||
|
||||
var entries = this._readdir(abs, inGlobStar)
|
||||
|
||||
// no entries means not a dir, so it can never have matches
|
||||
// foo.txt/** doesn't match foo.txt
|
||||
if (!entries)
|
||||
return
|
||||
|
||||
// test without the globstar, and with every child both below
|
||||
// and replacing the globstar.
|
||||
var remainWithoutGlobStar = remain.slice(1)
|
||||
var gspref = prefix ? [ prefix ] : []
|
||||
var noGlobStar = gspref.concat(remainWithoutGlobStar)
|
||||
|
||||
// the noGlobStar pattern exits the inGlobStar state
|
||||
this._process(noGlobStar, index, false)
|
||||
|
||||
var len = entries.length
|
||||
var isSym = this.symlinks[abs]
|
||||
|
||||
// If it's a symlink, and we're in a globstar, then stop
|
||||
if (isSym && inGlobStar)
|
||||
return
|
||||
|
||||
for (var i = 0; i < len; i++) {
|
||||
var e = entries[i]
|
||||
if (e.charAt(0) === '.' && !this.dot)
|
||||
continue
|
||||
|
||||
// these two cases enter the inGlobStar state
|
||||
var instead = gspref.concat(entries[i], remainWithoutGlobStar)
|
||||
this._process(instead, index, true)
|
||||
|
||||
var below = gspref.concat(entries[i], remain)
|
||||
this._process(below, index, true)
|
||||
}
|
||||
}
|
||||
|
||||
GlobSync.prototype._processSimple = function (prefix, index) {
|
||||
// XXX review this. Shouldn't it be doing the mounting etc
|
||||
// before doing stat? kinda weird?
|
||||
var exists = this._stat(prefix)
|
||||
|
||||
if (!this.matches[index])
|
||||
this.matches[index] = Object.create(null)
|
||||
|
||||
// If it doesn't exist, then just mark the lack of results
|
||||
if (!exists)
|
||||
return
|
||||
|
||||
if (prefix && isAbsolute(prefix) && !this.nomount) {
|
||||
var trail = /[\/\\]$/.test(prefix)
|
||||
if (prefix.charAt(0) === '/') {
|
||||
prefix = path.join(this.root, prefix)
|
||||
} else {
|
||||
prefix = path.resolve(this.root, prefix)
|
||||
if (trail)
|
||||
prefix += '/'
|
||||
}
|
||||
}
|
||||
|
||||
if (process.platform === 'win32')
|
||||
prefix = prefix.replace(/\\/g, '/')
|
||||
|
||||
// Mark this as a match
|
||||
this._emitMatch(index, prefix)
|
||||
}
|
||||
|
||||
// Returns either 'DIR', 'FILE', or false
|
||||
GlobSync.prototype._stat = function (f) {
|
||||
var abs = this._makeAbs(f)
|
||||
var needDir = f.slice(-1) === '/'
|
||||
|
||||
if (f.length > this.maxLength)
|
||||
return false
|
||||
|
||||
if (!this.stat && ownProp(this.cache, abs)) {
|
||||
var c = this.cache[abs]
|
||||
|
||||
if (Array.isArray(c))
|
||||
c = 'DIR'
|
||||
|
||||
// It exists, but maybe not how we need it
|
||||
if (!needDir || c === 'DIR')
|
||||
return c
|
||||
|
||||
if (needDir && c === 'FILE')
|
||||
return false
|
||||
|
||||
// otherwise we have to stat, because maybe c=true
|
||||
// if we know it exists, but not what it is.
|
||||
}
|
||||
|
||||
var exists
|
||||
var stat = this.statCache[abs]
|
||||
if (!stat) {
|
||||
var lstat
|
||||
try {
|
||||
lstat = fs.lstatSync(abs)
|
||||
} catch (er) {
|
||||
if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
|
||||
this.statCache[abs] = false
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
if (lstat && lstat.isSymbolicLink()) {
|
||||
try {
|
||||
stat = fs.statSync(abs)
|
||||
} catch (er) {
|
||||
stat = lstat
|
||||
}
|
||||
} else {
|
||||
stat = lstat
|
||||
}
|
||||
}
|
||||
|
||||
this.statCache[abs] = stat
|
||||
|
||||
var c = true
|
||||
if (stat)
|
||||
c = stat.isDirectory() ? 'DIR' : 'FILE'
|
||||
|
||||
this.cache[abs] = this.cache[abs] || c
|
||||
|
||||
if (needDir && c === 'FILE')
|
||||
return false
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
GlobSync.prototype._mark = function (p) {
|
||||
return common.mark(this, p)
|
||||
}
|
||||
|
||||
GlobSync.prototype._makeAbs = function (f) {
|
||||
return common.makeAbs(this, f)
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
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.
|
@ -0,0 +1,37 @@
|
||||
# inflight
|
||||
|
||||
Add callbacks to requests in flight to avoid async duplication
|
||||
|
||||
## USAGE
|
||||
|
||||
```javascript
|
||||
var inflight = require('inflight')
|
||||
|
||||
// some request that does some stuff
|
||||
function req(key, callback) {
|
||||
// key is any random string. like a url or filename or whatever.
|
||||
//
|
||||
// will return either a falsey value, indicating that the
|
||||
// request for this key is already in flight, or a new callback
|
||||
// which when called will call all callbacks passed to inflightk
|
||||
// with the same key
|
||||
callback = inflight(key, callback)
|
||||
|
||||
// If we got a falsey value back, then there's already a req going
|
||||
if (!callback) return
|
||||
|
||||
// this is where you'd fetch the url or whatever
|
||||
// callback is also once()-ified, so it can safely be assigned
|
||||
// to multiple events etc. First call wins.
|
||||
setTimeout(function() {
|
||||
callback(null, key)
|
||||
}, 100)
|
||||
}
|
||||
|
||||
// only assigns a single setTimeout
|
||||
// when it dings, all cbs get called
|
||||
req('foo', cb1)
|
||||
req('foo', cb2)
|
||||
req('foo', cb3)
|
||||
req('foo', cb4)
|
||||
```
|
@ -0,0 +1,54 @@
|
||||
var wrappy = require('wrappy')
|
||||
var reqs = Object.create(null)
|
||||
var once = require('once')
|
||||
|
||||
module.exports = wrappy(inflight)
|
||||
|
||||
function inflight (key, cb) {
|
||||
if (reqs[key]) {
|
||||
reqs[key].push(cb)
|
||||
return null
|
||||
} else {
|
||||
reqs[key] = [cb]
|
||||
return makeres(key)
|
||||
}
|
||||
}
|
||||
|
||||
function makeres (key) {
|
||||
return once(function RES () {
|
||||
var cbs = reqs[key]
|
||||
var len = cbs.length
|
||||
var args = slice(arguments)
|
||||
|
||||
// XXX It's somewhat ambiguous whether a new callback added in this
|
||||
// pass should be queued for later execution if something in the
|
||||
// list of callbacks throws, or if it should just be discarded.
|
||||
// However, it's such an edge case that it hardly matters, and either
|
||||
// choice is likely as surprising as the other.
|
||||
// As it happens, we do go ahead and schedule it for later execution.
|
||||
try {
|
||||
for (var i = 0; i < len; i++) {
|
||||
cbs[i].apply(null, args)
|
||||
}
|
||||
} finally {
|
||||
if (cbs.length > len) {
|
||||
// added more in the interim.
|
||||
// de-zalgo, just in case, but don't call again.
|
||||
cbs.splice(0, len)
|
||||
process.nextTick(function () {
|
||||
RES.apply(null, args)
|
||||
})
|
||||
} else {
|
||||
delete reqs[key]
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function slice (args) {
|
||||
var length = args.length
|
||||
var array = []
|
||||
|
||||
for (var i = 0; i < length; i++) array[i] = args[i]
|
||||
return array
|
||||
}
|
@ -0,0 +1,58 @@
|
||||
{
|
||||
"_from": "inflight@^1.0.4",
|
||||
"_id": "inflight@1.0.6",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=",
|
||||
"_location": "/inflight",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "inflight@^1.0.4",
|
||||
"name": "inflight",
|
||||
"escapedName": "inflight",
|
||||
"rawSpec": "^1.0.4",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "^1.0.4"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/glob"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
|
||||
"_shasum": "49bd6331d7d02d0c09bc910a1075ba8165b56df9",
|
||||
"_spec": "inflight@^1.0.4",
|
||||
"_where": "/Users/paolo/Desktop/multiplayer games/likelike-online/node_modules/glob",
|
||||
"author": {
|
||||
"name": "Isaac Z. Schlueter",
|
||||
"email": "i@izs.me",
|
||||
"url": "http://blog.izs.me/"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/isaacs/inflight/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"dependencies": {
|
||||
"once": "^1.3.0",
|
||||
"wrappy": "1"
|
||||
},
|
||||
"deprecated": false,
|
||||
"description": "Add callbacks to requests in flight to avoid async duplication",
|
||||
"devDependencies": {
|
||||
"tap": "^7.1.2"
|
||||
},
|
||||
"files": [
|
||||
"inflight.js"
|
||||
],
|
||||
"homepage": "https://github.com/isaacs/inflight",
|
||||
"license": "ISC",
|
||||
"main": "inflight.js",
|
||||
"name": "inflight",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/npm/inflight.git"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "tap test.js --100"
|
||||
},
|
||||
"version": "1.0.6"
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
The ISC License
|
||||
|
||||
Copyright (c) Isaac Z. Schlueter and Contributors
|
||||
|
||||
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.
|
@ -0,0 +1,209 @@
|
||||
# minimatch
|
||||
|
||||
A minimal matching utility.
|
||||
|
||||
[![Build Status](https://secure.travis-ci.org/isaacs/minimatch.svg)](http://travis-ci.org/isaacs/minimatch)
|
||||
|
||||
|
||||
This is the matching library used internally by npm.
|
||||
|
||||
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 instantiating 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.
|
||||
|
||||
### 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 if this option is set. When not 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.
|
@ -0,0 +1,923 @@
|
||||
module.exports = minimatch
|
||||
minimatch.Minimatch = Minimatch
|
||||
|
||||
var path = { sep: '/' }
|
||||
try {
|
||||
path = require('path')
|
||||
} catch (er) {}
|
||||
|
||||
var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}
|
||||
var expand = require('brace-expansion')
|
||||
|
||||
var plTypes = {
|
||||
'!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
|
||||
'?': { open: '(?:', close: ')?' },
|
||||
'+': { open: '(?:', close: ')+' },
|
||||
'*': { open: '(?:', close: ')*' },
|
||||
'@': { open: '(?:', close: ')' }
|
||||
}
|
||||
|
||||
// any single thing other than /
|
||||
// don't need to escape / when using new RegExp()
|
||||
var qmark = '[^/]'
|
||||
|
||||
// * => any number of characters
|
||||
var star = qmark + '*?'
|
||||
|
||||
// ** when dots are allowed. Anything goes, except .. and .
|
||||
// not (^ or / followed by one or two dots followed by $ or /),
|
||||
// followed by anything, any number of times.
|
||||
var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'
|
||||
|
||||
// not a ^ or / followed by a dot,
|
||||
// followed by anything, any number of times.
|
||||
var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'
|
||||
|
||||
// characters that need to be escaped in RegExp.
|
||||
var reSpecials = charSet('().*{}+?[]^$\\!')
|
||||
|
||||
// "abc" -> { a:true, b:true, c:true }
|
||||
function charSet (s) {
|
||||
return s.split('').reduce(function (set, c) {
|
||||
set[c] = true
|
||||
return set
|
||||
}, {})
|
||||
}
|
||||
|
||||
// normalizes slashes.
|
||||
var slashSplit = /\/+/
|
||||
|
||||
minimatch.filter = filter
|
||||
function filter (pattern, options) {
|
||||
options = options || {}
|
||||
return function (p, i, list) {
|
||||
return minimatch(p, pattern, options)
|
||||
}
|
||||
}
|
||||
|
||||
function ext (a, b) {
|
||||
a = a || {}
|
||||
b = b || {}
|
||||
var t = {}
|
||||
Object.keys(b).forEach(function (k) {
|
||||
t[k] = b[k]
|
||||
})
|
||||
Object.keys(a).forEach(function (k) {
|
||||
t[k] = a[k]
|
||||
})
|
||||
return t
|
||||
}
|
||||
|
||||
minimatch.defaults = function (def) {
|
||||
if (!def || !Object.keys(def).length) return minimatch
|
||||
|
||||
var orig = minimatch
|
||||
|
||||
var m = function minimatch (p, pattern, options) {
|
||||
return orig.minimatch(p, pattern, ext(def, options))
|
||||
}
|
||||
|
||||
m.Minimatch = function Minimatch (pattern, options) {
|
||||
return new orig.Minimatch(pattern, ext(def, options))
|
||||
}
|
||||
|
||||
return m
|
||||
}
|
||||
|
||||
Minimatch.defaults = function (def) {
|
||||
if (!def || !Object.keys(def).length) return Minimatch
|
||||
return minimatch.defaults(def).Minimatch
|
||||
}
|
||||
|
||||
function minimatch (p, pattern, options) {
|
||||
if (typeof pattern !== 'string') {
|
||||
throw new TypeError('glob pattern string required')
|
||||
}
|
||||
|
||||
if (!options) options = {}
|
||||
|
||||
// shortcut: comments match nothing.
|
||||
if (!options.nocomment && pattern.charAt(0) === '#') {
|
||||
return false
|
||||
}
|
||||
|
||||
// "" only matches ""
|
||||
if (pattern.trim() === '') return p === ''
|
||||
|
||||
return new Minimatch(pattern, options).match(p)
|
||||
}
|
||||
|
||||
function Minimatch (pattern, options) {
|
||||
if (!(this instanceof Minimatch)) {
|
||||
return new Minimatch(pattern, options)
|
||||
}
|
||||
|
||||
if (typeof pattern !== 'string') {
|
||||
throw new TypeError('glob pattern string required')
|
||||
}
|
||||
|
||||
if (!options) options = {}
|
||||
pattern = pattern.trim()
|
||||
|
||||
// windows support: need to use /, not \
|
||||
if (path.sep !== '/') {
|
||||
pattern = pattern.split(path.sep).join('/')
|
||||
}
|
||||
|
||||
this.options = options
|
||||
this.set = []
|
||||
this.pattern = pattern
|
||||
this.regexp = null
|
||||
this.negate = false
|
||||
this.comment = false
|
||||
this.empty = false
|
||||
|
||||
// make the set of regexps etc.
|
||||
this.make()
|
||||
}
|
||||
|
||||
Minimatch.prototype.debug = function () {}
|
||||
|
||||
Minimatch.prototype.make = make
|
||||
function make () {
|
||||
// don't do it more than once.
|
||||
if (this._made) return
|
||||
|
||||
var pattern = this.pattern
|
||||
var options = this.options
|
||||
|
||||
// empty patterns and comments match nothing.
|
||||
if (!options.nocomment && pattern.charAt(0) === '#') {
|
||||
this.comment = true
|
||||
return
|
||||
}
|
||||
if (!pattern) {
|
||||
this.empty = true
|
||||
return
|
||||
}
|
||||
|
||||
// step 1: figure out negation, etc.
|
||||
this.parseNegate()
|
||||
|
||||
// step 2: expand braces
|
||||
var set = this.globSet = this.braceExpand()
|
||||
|
||||
if (options.debug) this.debug = console.error
|
||||
|
||||
this.debug(this.pattern, set)
|
||||
|
||||
// step 3: now we have a set, so turn each one into a series of path-portion
|
||||
// matching patterns.
|
||||
// These will be regexps, except in the case of "**", which is
|
||||
// set to the GLOBSTAR object for globstar behavior,
|
||||
// and will not contain any / characters
|
||||
set = this.globParts = set.map(function (s) {
|
||||
return s.split(slashSplit)
|
||||
})
|
||||
|
||||
this.debug(this.pattern, set)
|
||||
|
||||
// glob --> regexps
|
||||
set = set.map(function (s, si, set) {
|
||||
return s.map(this.parse, this)
|
||||
}, this)
|
||||
|
||||
this.debug(this.pattern, set)
|
||||
|
||||
// filter out everything that didn't compile properly.
|
||||
set = set.filter(function (s) {
|
||||
return s.indexOf(false) === -1
|
||||
})
|
||||
|
||||
this.debug(this.pattern, set)
|
||||
|
||||
this.set = set
|
||||
}
|
||||
|
||||
Minimatch.prototype.parseNegate = parseNegate
|
||||
function parseNegate () {
|
||||
var pattern = this.pattern
|
||||
var negate = false
|
||||
var options = this.options
|
||||
var negateOffset = 0
|
||||
|
||||
if (options.nonegate) return
|
||||
|
||||
for (var i = 0, l = pattern.length
|
||||
; i < l && pattern.charAt(i) === '!'
|
||||
; i++) {
|
||||
negate = !negate
|
||||
negateOffset++
|
||||
}
|
||||
|
||||
if (negateOffset) this.pattern = pattern.substr(negateOffset)
|
||||
this.negate = negate
|
||||
}
|
||||
|
||||
// Brace expansion:
|
||||
// a{b,c}d -> abd acd
|
||||
// a{b,}c -> abc ac
|
||||
// a{0..3}d -> a0d a1d a2d a3d
|
||||
// a{b,c{d,e}f}g -> abg acdfg acefg
|
||||
// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
|
||||
//
|
||||
// Invalid sets are not expanded.
|
||||
// a{2..}b -> a{2..}b
|
||||
// a{b}c -> a{b}c
|
||||
minimatch.braceExpand = function (pattern, options) {
|
||||
return braceExpand(pattern, options)
|
||||
}
|
||||
|
||||
Minimatch.prototype.braceExpand = braceExpand
|
||||
|
||||
function braceExpand (pattern, options) {
|
||||
if (!options) {
|
||||
if (this instanceof Minimatch) {
|
||||
options = this.options
|
||||
} else {
|
||||
options = {}
|
||||
}
|
||||
}
|
||||
|
||||
pattern = typeof pattern === 'undefined'
|
||||
? this.pattern : pattern
|
||||
|
||||
if (typeof pattern === 'undefined') {
|
||||
throw new TypeError('undefined pattern')
|
||||
}
|
||||
|
||||
if (options.nobrace ||
|
||||
!pattern.match(/\{.*\}/)) {
|
||||
// shortcut. no need to expand.
|
||||
return [pattern]
|
||||
}
|
||||
|
||||
return expand(pattern)
|
||||
}
|
||||
|
||||
// parse a component of the expanded set.
|
||||
// At this point, no pattern may contain "/" in it
|
||||
// so we're going to return a 2d array, where each entry is the full
|
||||
// pattern, split on '/', and then turned into a regular expression.
|
||||
// A regexp is made at the end which joins each array with an
|
||||
// escaped /, and another full one which joins each regexp with |.
|
||||
//
|
||||
// Following the lead of Bash 4.1, note that "**" only has special meaning
|
||||
// when it is the *only* thing in a path portion. Otherwise, any series
|
||||
// of * is equivalent to a single *. Globstar behavior is enabled by
|
||||
// default, and can be disabled by setting options.noglobstar.
|
||||
Minimatch.prototype.parse = parse
|
||||
var SUBPARSE = {}
|
||||
function parse (pattern, isSub) {
|
||||
if (pattern.length > 1024 * 64) {
|
||||
throw new TypeError('pattern is too long')
|
||||
}
|
||||
|
||||
var options = this.options
|
||||
|
||||
// shortcuts
|
||||
if (!options.noglobstar && pattern === '**') return GLOBSTAR
|
||||
if (pattern === '') return ''
|
||||
|
||||
var re = ''
|
||||
var hasMagic = !!options.nocase
|
||||
var escaping = false
|
||||
// ? => one single character
|
||||
var patternListStack = []
|
||||
var negativeLists = []
|
||||
var stateChar
|
||||
var inClass = false
|
||||
var reClassStart = -1
|
||||
var classStart = -1
|
||||
// . and .. never match anything that doesn't start with .,
|
||||
// even when options.dot is set.
|
||||
var patternStart = pattern.charAt(0) === '.' ? '' // anything
|
||||
// not (start or / followed by . or .. followed by / or end)
|
||||
: options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
|
||||
: '(?!\\.)'
|
||||
var self = this
|
||||
|
||||
function clearStateChar () {
|
||||
if (stateChar) {
|
||||
// we had some state-tracking character
|
||||
// that wasn't consumed by this pass.
|
||||
switch (stateChar) {
|
||||
case '*':
|
||||
re += star
|
||||
hasMagic = true
|
||||
break
|
||||
case '?':
|
||||
re += qmark
|
||||
hasMagic = true
|
||||
break
|
||||
default:
|
||||
re += '\\' + stateChar
|
||||
break
|
||||
}
|
||||
self.debug('clearStateChar %j %j', stateChar, re)
|
||||
stateChar = false
|
||||
}
|
||||
}
|
||||
|
||||
for (var i = 0, len = pattern.length, c
|
||||
; (i < len) && (c = pattern.charAt(i))
|
||||
; i++) {
|
||||
this.debug('%s\t%s %s %j', pattern, i, re, c)
|
||||
|
||||
// skip over any that are escaped.
|
||||
if (escaping && reSpecials[c]) {
|
||||
re += '\\' + c
|
||||
escaping = false
|
||||
continue
|
||||
}
|
||||
|
||||
switch (c) {
|
||||
case '/':
|
||||
// completely not allowed, even escaped.
|
||||
// Should already be path-split by now.
|
||||
return false
|
||||
|
||||
case '\\':
|
||||
clearStateChar()
|
||||
escaping = true
|
||||
continue
|
||||
|
||||
// the various stateChar values
|
||||
// for the "extglob" stuff.
|
||||
case '?':
|
||||
case '*':
|
||||
case '+':
|
||||
case '@':
|
||||
case '!':
|
||||
this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c)
|
||||
|
||||
// all of those are literals inside a class, except that
|
||||
// the glob [!a] means [^a] in regexp
|
||||
if (inClass) {
|
||||
this.debug(' in class')
|
||||
if (c === '!' && i === classStart + 1) c = '^'
|
||||
re += c
|
||||
continue
|
||||
}
|
||||
|
||||
// if we already have a stateChar, then it means
|
||||
// that there was something like ** or +? in there.
|
||||
// Handle the stateChar, then proceed with this one.
|
||||
self.debug('call clearStateChar %j', stateChar)
|
||||
clearStateChar()
|
||||
stateChar = c
|
||||
// if extglob is disabled, then +(asdf|foo) isn't a thing.
|
||||
// just clear the statechar *now*, rather than even diving into
|
||||
// the patternList stuff.
|
||||
if (options.noext) clearStateChar()
|
||||
continue
|
||||
|
||||
case '(':
|
||||
if (inClass) {
|
||||
re += '('
|
||||
continue
|
||||
}
|
||||
|
||||
if (!stateChar) {
|
||||
re += '\\('
|
||||
continue
|
||||
}
|
||||
|
||||
patternListStack.push({
|
||||
type: stateChar,
|
||||
start: i - 1,
|
||||
reStart: re.length,
|
||||
open: plTypes[stateChar].open,
|
||||
close: plTypes[stateChar].close
|
||||
})
|
||||
// negation is (?:(?!js)[^/]*)
|
||||
re += stateChar === '!' ? '(?:(?!(?:' : '(?:'
|
||||
this.debug('plType %j %j', stateChar, re)
|
||||
stateChar = false
|
||||
continue
|
||||
|
||||
case ')':
|
||||
if (inClass || !patternListStack.length) {
|
||||
re += '\\)'
|
||||
continue
|
||||
}
|
||||
|
||||
clearStateChar()
|
||||
hasMagic = true
|
||||
var pl = patternListStack.pop()
|
||||
// negation is (?:(?!js)[^/]*)
|
||||
// The others are (?:<pattern>)<type>
|
||||
re += pl.close
|
||||
if (pl.type === '!') {
|
||||
negativeLists.push(pl)
|
||||
}
|
||||
pl.reEnd = re.length
|
||||
continue
|
||||
|
||||
case '|':
|
||||
if (inClass || !patternListStack.length || escaping) {
|
||||
re += '\\|'
|
||||
escaping = false
|
||||
continue
|
||||
}
|
||||
|
||||
clearStateChar()
|
||||
re += '|'
|
||||
continue
|
||||
|
||||
// these are mostly the same in regexp and glob
|
||||
case '[':
|
||||
// swallow any state-tracking char before the [
|
||||
clearStateChar()
|
||||
|
||||
if (inClass) {
|
||||
re += '\\' + c
|
||||
continue
|
||||
}
|
||||
|
||||
inClass = true
|
||||
classStart = i
|
||||
reClassStart = re.length
|
||||
re += c
|
||||
continue
|
||||
|
||||
case ']':
|
||||
// a right bracket shall lose its special
|
||||
// meaning and represent itself in
|
||||
// a bracket expression if it occurs
|
||||
// first in the list. -- POSIX.2 2.8.3.2
|
||||
if (i === classStart + 1 || !inClass) {
|
||||
re += '\\' + c
|
||||
escaping = false
|
||||
continue
|
||||
}
|
||||
|
||||
// handle the case where we left a class open.
|
||||
// "[z-a]" is valid, equivalent to "\[z-a\]"
|
||||
if (inClass) {
|
||||
// split where the last [ was, make sure we don't have
|
||||
// an invalid re. if so, re-walk the contents of the
|
||||
// would-be class to re-translate any characters that
|
||||
// were passed through as-is
|
||||
// TODO: It would probably be faster to determine this
|
||||
// without a try/catch and a new RegExp, but it's tricky
|
||||
// to do safely. For now, this is safe and works.
|
||||
var cs = pattern.substring(classStart + 1, i)
|
||||
try {
|
||||
RegExp('[' + cs + ']')
|
||||
} catch (er) {
|
||||
// not a valid class!
|
||||
var sp = this.parse(cs, SUBPARSE)
|
||||
re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'
|
||||
hasMagic = hasMagic || sp[1]
|
||||
inClass = false
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// finish up the class.
|
||||
hasMagic = true
|
||||
inClass = false
|
||||
re += c
|
||||
continue
|
||||
|
||||
default:
|
||||
// swallow any state char that wasn't consumed
|
||||
clearStateChar()
|
||||
|
||||
if (escaping) {
|
||||
// no need
|
||||
escaping = false
|
||||
} else if (reSpecials[c]
|
||||
&& !(c === '^' && inClass)) {
|
||||
re += '\\'
|
||||
}
|
||||
|
||||
re += c
|
||||
|
||||
} // switch
|
||||
} // for
|
||||
|
||||
// handle the case where we left a class open.
|
||||
// "[abc" is valid, equivalent to "\[abc"
|
||||
if (inClass) {
|
||||
// split where the last [ was, and escape it
|
||||
// this is a huge pita. We now have to re-walk
|
||||
// the contents of the would-be class to re-translate
|
||||
// any characters that were passed through as-is
|
||||
cs = pattern.substr(classStart + 1)
|
||||
sp = this.parse(cs, SUBPARSE)
|
||||
re = re.substr(0, reClassStart) + '\\[' + sp[0]
|
||||
hasMagic = hasMagic || sp[1]
|
||||
}
|
||||
|
||||
// handle the case where we had a +( thing at the *end*
|
||||
// of the pattern.
|
||||
// each pattern list stack adds 3 chars, and we need to go through
|
||||
// and escape any | chars that were passed through as-is for the regexp.
|
||||
// Go through and escape them, taking care not to double-escape any
|
||||
// | chars that were already escaped.
|
||||
for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
|
||||
var tail = re.slice(pl.reStart + pl.open.length)
|
||||
this.debug('setting tail', re, pl)
|
||||
// maybe some even number of \, then maybe 1 \, followed by a |
|
||||
tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
|
||||
if (!$2) {
|
||||
// the | isn't already escaped, so escape it.
|
||||
$2 = '\\'
|
||||
}
|
||||
|
||||
// need to escape all those slashes *again*, without escaping the
|
||||
// one that we need for escaping the | character. As it works out,
|
||||
// escaping an even number of slashes can be done by simply repeating
|
||||
// it exactly after itself. That's why this trick works.
|
||||
//
|
||||
// I am sorry that you have to see this.
|
||||
return $1 + $1 + $2 + '|'
|
||||
})
|
||||
|
||||
this.debug('tail=%j\n %s', tail, tail, pl, re)
|
||||
var t = pl.type === '*' ? star
|
||||
: pl.type === '?' ? qmark
|
||||
: '\\' + pl.type
|
||||
|
||||
hasMagic = true
|
||||
re = re.slice(0, pl.reStart) + t + '\\(' + tail
|
||||
}
|
||||
|
||||
// handle trailing things that only matter at the very end.
|
||||
clearStateChar()
|
||||
if (escaping) {
|
||||
// trailing \\
|
||||
re += '\\\\'
|
||||
}
|
||||
|
||||
// only need to apply the nodot start if the re starts with
|
||||
// something that could conceivably capture a dot
|
||||
var addPatternStart = false
|
||||
switch (re.charAt(0)) {
|
||||
case '.':
|
||||
case '[':
|
||||
case '(': addPatternStart = true
|
||||
}
|
||||
|
||||
// Hack to work around lack of negative lookbehind in JS
|
||||
// A pattern like: *.!(x).!(y|z) needs to ensure that a name
|
||||
// like 'a.xyz.yz' doesn't match. So, the first negative
|
||||
// lookahead, has to look ALL the way ahead, to the end of
|
||||
// the pattern.
|
||||
for (var n = negativeLists.length - 1; n > -1; n--) {
|
||||
var nl = negativeLists[n]
|
||||
|
||||
var nlBefore = re.slice(0, nl.reStart)
|
||||
var nlFirst = re.slice(nl.reStart, nl.reEnd - 8)
|
||||
var nlLast = re.slice(nl.reEnd - 8, nl.reEnd)
|
||||
var nlAfter = re.slice(nl.reEnd)
|
||||
|
||||
nlLast += nlAfter
|
||||
|
||||
// Handle nested stuff like *(*.js|!(*.json)), where open parens
|
||||
// mean that we should *not* include the ) in the bit that is considered
|
||||
// "after" the negated section.
|
||||
var openParensBefore = nlBefore.split('(').length - 1
|
||||
var cleanAfter = nlAfter
|
||||
for (i = 0; i < openParensBefore; i++) {
|
||||
cleanAfter = cleanAfter.replace(/\)[+*?]?/, '')
|
||||
}
|
||||
nlAfter = cleanAfter
|
||||
|
||||
var dollar = ''
|
||||
if (nlAfter === '' && isSub !== SUBPARSE) {
|
||||
dollar = '$'
|
||||
}
|
||||
var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast
|
||||
re = newRe
|
||||
}
|
||||
|
||||
// if the re is not "" at this point, then we need to make sure
|
||||
// it doesn't match against an empty path part.
|
||||
// Otherwise a/* will match a/, which it should not.
|
||||
if (re !== '' && hasMagic) {
|
||||
re = '(?=.)' + re
|
||||
}
|
||||
|
||||
if (addPatternStart) {
|
||||
re = patternStart + re
|
||||
}
|
||||
|
||||
// parsing just a piece of a larger pattern.
|
||||
if (isSub === SUBPARSE) {
|
||||
return [re, hasMagic]
|
||||
}
|
||||
|
||||
// skip the regexp for non-magical patterns
|
||||
// unescape anything in it, though, so that it'll be
|
||||
// an exact match against a file etc.
|
||||
if (!hasMagic) {
|
||||
return globUnescape(pattern)
|
||||
}
|
||||
|
||||
var flags = options.nocase ? 'i' : ''
|
||||
try {
|
||||
var regExp = new RegExp('^' + re + '$', flags)
|
||||
} catch (er) {
|
||||
// If it was an invalid regular expression, then it can't match
|
||||
// anything. This trick looks for a character after the end of
|
||||
// the string, which is of course impossible, except in multi-line
|
||||
// mode, but it's not a /m regex.
|
||||
return new RegExp('$.')
|
||||
}
|
||||
|
||||
regExp._glob = pattern
|
||||
regExp._src = re
|
||||
|
||||
return regExp
|
||||
}
|
||||
|
||||
minimatch.makeRe = function (pattern, options) {
|
||||
return new Minimatch(pattern, options || {}).makeRe()
|
||||
}
|
||||
|
||||
Minimatch.prototype.makeRe = makeRe
|
||||
function makeRe () {
|
||||
if (this.regexp || this.regexp === false) return this.regexp
|
||||
|
||||
// at this point, this.set is a 2d array of partial
|
||||
// pattern strings, or "**".
|
||||
//
|
||||
// It's better to use .match(). This function shouldn't
|
||||
// be used, really, but it's pretty convenient sometimes,
|
||||
// when you just want to work with a regex.
|
||||
var set = this.set
|
||||
|
||||
if (!set.length) {
|
||||
this.regexp = false
|
||||
return this.regexp
|
||||
}
|
||||
var options = this.options
|
||||
|
||||
var twoStar = options.noglobstar ? star
|
||||
: options.dot ? twoStarDot
|
||||
: twoStarNoDot
|
||||
var flags = options.nocase ? 'i' : ''
|
||||
|
||||
var re = set.map(function (pattern) {
|
||||
return pattern.map(function (p) {
|
||||
return (p === GLOBSTAR) ? twoStar
|
||||
: (typeof p === 'string') ? regExpEscape(p)
|
||||
: p._src
|
||||
}).join('\\\/')
|
||||
}).join('|')
|
||||
|
||||
// must match entire pattern
|
||||
// ending in a * or ** will make it less strict.
|
||||
re = '^(?:' + re + ')$'
|
||||
|
||||
// can match anything, as long as it's not this.
|
||||
if (this.negate) re = '^(?!' + re + ').*$'
|
||||
|
||||
try {
|
||||
this.regexp = new RegExp(re, flags)
|
||||
} catch (ex) {
|
||||
this.regexp = false
|
||||
}
|
||||
return this.regexp
|
||||
}
|
||||
|
||||
minimatch.match = function (list, pattern, options) {
|
||||
options = options || {}
|
||||
var mm = new Minimatch(pattern, options)
|
||||
list = list.filter(function (f) {
|
||||
return mm.match(f)
|
||||
})
|
||||
if (mm.options.nonull && !list.length) {
|
||||
list.push(pattern)
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
Minimatch.prototype.match = match
|
||||
function match (f, partial) {
|
||||
this.debug('match', f, this.pattern)
|
||||
// short-circuit in the case of busted things.
|
||||
// comments, etc.
|
||||
if (this.comment) return false
|
||||
if (this.empty) return f === ''
|
||||
|
||||
if (f === '/' && partial) return true
|
||||
|
||||
var options = this.options
|
||||
|
||||
// windows: need to use /, not \
|
||||
if (path.sep !== '/') {
|
||||
f = f.split(path.sep).join('/')
|
||||
}
|
||||
|
||||
// treat the test path as a set of pathparts.
|
||||
f = f.split(slashSplit)
|
||||
this.debug(this.pattern, 'split', f)
|
||||
|
||||
// just ONE of the pattern sets in this.set needs to match
|
||||
// in order for it to be valid. If negating, then just one
|
||||
// match means that we have failed.
|
||||
// Either way, return on the first hit.
|
||||
|
||||
var set = this.set
|
||||
this.debug(this.pattern, 'set', set)
|
||||
|
||||
// Find the basename of the path by looking for the last non-empty segment
|
||||
var filename
|
||||
var i
|
||||
for (i = f.length - 1; i >= 0; i--) {
|
||||
filename = f[i]
|
||||
if (filename) break
|
||||
}
|
||||
|
||||
for (i = 0; i < set.length; i++) {
|
||||
var pattern = set[i]
|
||||
var file = f
|
||||
if (options.matchBase && pattern.length === 1) {
|
||||
file = [filename]
|
||||
}
|
||||
var hit = this.matchOne(file, pattern, partial)
|
||||
if (hit) {
|
||||
if (options.flipNegate) return true
|
||||
return !this.negate
|
||||
}
|
||||
}
|
||||
|
||||
// didn't get any hits. this is success if it's a negative
|
||||
// pattern, failure otherwise.
|
||||
if (options.flipNegate) return false
|
||||
return this.negate
|
||||
}
|
||||
|
||||
// set partial to true to test if, for example,
|
||||
// "/a/b" matches the start of "/*/b/*/d"
|
||||
// Partial means, if you run out of file before you run
|
||||
// out of pattern, then that's fine, as long as all
|
||||
// the parts match.
|
||||
Minimatch.prototype.matchOne = function (file, pattern, partial) {
|
||||
var options = this.options
|
||||
|
||||
this.debug('matchOne',
|
||||
{ 'this': this, file: file, pattern: pattern })
|
||||
|
||||
this.debug('matchOne', file.length, pattern.length)
|
||||
|
||||
for (var fi = 0,
|
||||
pi = 0,
|
||||
fl = file.length,
|
||||
pl = pattern.length
|
||||
; (fi < fl) && (pi < pl)
|
||||
; fi++, pi++) {
|
||||
this.debug('matchOne loop')
|
||||
var p = pattern[pi]
|
||||
var f = file[fi]
|
||||
|
||||
this.debug(pattern, p, f)
|
||||
|
||||
// should be impossible.
|
||||
// some invalid regexp stuff in the set.
|
||||
if (p === false) return false
|
||||
|
||||
if (p === GLOBSTAR) {
|
||||
this.debug('GLOBSTAR', [pattern, p, f])
|
||||
|
||||
// "**"
|
||||
// a/**/b/**/c would match the following:
|
||||
// a/b/x/y/z/c
|
||||
// a/x/y/z/b/c
|
||||
// a/b/x/b/x/c
|
||||
// a/b/c
|
||||
// To do this, take the rest of the pattern after
|
||||
// the **, and see if it would match the file remainder.
|
||||
// If so, return success.
|
||||
// If not, the ** "swallows" a segment, and try again.
|
||||
// This is recursively awful.
|
||||
//
|
||||
// a/**/b/**/c matching a/b/x/y/z/c
|
||||
// - a matches a
|
||||
// - doublestar
|
||||
// - matchOne(b/x/y/z/c, b/**/c)
|
||||
// - b matches b
|
||||
// - doublestar
|
||||
// - matchOne(x/y/z/c, c) -> no
|
||||
// - matchOne(y/z/c, c) -> no
|
||||
// - matchOne(z/c, c) -> no
|
||||
// - matchOne(c, c) yes, hit
|
||||
var fr = fi
|
||||
var pr = pi + 1
|
||||
if (pr === pl) {
|
||||
this.debug('** at the end')
|
||||
// a ** at the end will just swallow the rest.
|
||||
// We have found a match.
|
||||
// however, it will not swallow /.x, unless
|
||||
// options.dot is set.
|
||||
// . and .. are *never* matched by **, for explosively
|
||||
// exponential reasons.
|
||||
for (; fi < fl; fi++) {
|
||||
if (file[fi] === '.' || file[fi] === '..' ||
|
||||
(!options.dot && file[fi].charAt(0) === '.')) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ok, let's see if we can swallow whatever we can.
|
||||
while (fr < fl) {
|
||||
var swallowee = file[fr]
|
||||
|
||||
this.debug('\nglobstar while', file, fr, pattern, pr, swallowee)
|
||||
|
||||
// XXX remove this slice. Just pass the start index.
|
||||
if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
|
||||
this.debug('globstar found match!', fr, fl, swallowee)
|
||||
// found a match.
|
||||
return true
|
||||
} else {
|
||||
// can't swallow "." or ".." ever.
|
||||
// can only swallow ".foo" when explicitly asked.
|
||||
if (swallowee === '.' || swallowee === '..' ||
|
||||
(!options.dot && swallowee.charAt(0) === '.')) {
|
||||
this.debug('dot detected!', file, fr, pattern, pr)
|
||||
break
|
||||
}
|
||||
|
||||
// ** swallows a segment, and continue.
|
||||
this.debug('globstar swallow a segment, and continue')
|
||||
fr++
|
||||
}
|
||||
}
|
||||
|
||||
// no match was found.
|
||||
// However, in partial mode, we can't say this is necessarily over.
|
||||
// If there's more *pattern* left, then
|
||||
if (partial) {
|
||||
// ran out of file
|
||||
this.debug('\n>>> no match, partial?', file, fr, pattern, pr)
|
||||
if (fr === fl) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// something other than **
|
||||
// non-magic patterns just have to match exactly
|
||||
// patterns with magic have been turned into regexps.
|
||||
var hit
|
||||
if (typeof p === 'string') {
|
||||
if (options.nocase) {
|
||||
hit = f.toLowerCase() === p.toLowerCase()
|
||||
} else {
|
||||
hit = f === p
|
||||
}
|
||||
this.debug('string match', p, f, hit)
|
||||
} else {
|
||||
hit = f.match(p)
|
||||
this.debug('pattern match', p, f, hit)
|
||||
}
|
||||
|
||||
if (!hit) return false
|
||||
}
|
||||
|
||||
// Note: ending in / means that we'll get a final ""
|
||||
// at the end of the pattern. This can only match a
|
||||
// corresponding "" at the end of the file.
|
||||
// If the file ends in /, then it can only match a
|
||||
// a pattern that ends in /, unless the pattern just
|
||||
// doesn't have any more for it. But, a/b/ should *not*
|
||||
// match "a/b/*", even though "" matches against the
|
||||
// [^/]*? pattern, except in partial mode, where it might
|
||||
// simply not be reached yet.
|
||||
// However, a/b/ should still satisfy a/*
|
||||
|
||||
// now either we fell off the end of the pattern, or we're done.
|
||||
if (fi === fl && pi === pl) {
|
||||
// ran out of pattern and filename at the same time.
|
||||
// an exact hit!
|
||||
return true
|
||||
} else if (fi === fl) {
|
||||
// ran out of file, but still had pattern left.
|
||||
// this is ok if we're doing the match as part of
|
||||
// a glob fs traversal.
|
||||
return partial
|
||||
} else if (pi === pl) {
|
||||
// ran out of pattern, still have file left.
|
||||
// this is only acceptable if we're on the very last
|
||||
// empty segment of a file with a trailing slash.
|
||||
// a/* should match a/b/
|
||||
var emptyFileEnd = (fi === fl - 1) && (file[fi] === '')
|
||||
return emptyFileEnd
|
||||
}
|
||||
|
||||
// should be unreachable.
|
||||
throw new Error('wtf?')
|
||||
}
|
||||
|
||||
// replace stuff like \* with *
|
||||
function globUnescape (s) {
|
||||
return s.replace(/\\(.)/g, '$1')
|
||||
}
|
||||
|
||||
function regExpEscape (s) {
|
||||
return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
|
||||
}
|
@ -0,0 +1,63 @@
|
||||
{
|
||||
"_from": "minimatch@^3.0.4",
|
||||
"_id": "minimatch@3.0.4",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==",
|
||||
"_location": "/minimatch",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "minimatch@^3.0.4",
|
||||
"name": "minimatch",
|
||||
"escapedName": "minimatch",
|
||||
"rawSpec": "^3.0.4",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "^3.0.4"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/glob"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz",
|
||||
"_shasum": "5166e286457f03306064be5497e8dbb0c3d32083",
|
||||
"_spec": "minimatch@^3.0.4",
|
||||
"_where": "/Users/paolo/Desktop/multiplayer games/likelike-online/node_modules/glob",
|
||||
"author": {
|
||||
"name": "Isaac Z. Schlueter",
|
||||
"email": "i@izs.me",
|
||||
"url": "http://blog.izs.me"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/isaacs/minimatch/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"dependencies": {
|
||||
"brace-expansion": "^1.1.7"
|
||||
},
|
||||
"deprecated": false,
|
||||
"description": "a glob matcher in javascript",
|
||||
"devDependencies": {
|
||||
"tap": "^10.3.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": "*"
|
||||
},
|
||||
"files": [
|
||||
"minimatch.js"
|
||||
],
|
||||
"homepage": "https://github.com/isaacs/minimatch#readme",
|
||||
"license": "ISC",
|
||||
"main": "minimatch.js",
|
||||
"name": "minimatch",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/isaacs/minimatch.git"
|
||||
},
|
||||
"scripts": {
|
||||
"postpublish": "git push origin --all; git push origin --tags",
|
||||
"postversion": "npm publish",
|
||||
"preversion": "npm test",
|
||||
"test": "tap test/*.js --cov"
|
||||
},
|
||||
"version": "3.0.4"
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
The ISC License
|
||||
|
||||
Copyright (c) Isaac Z. Schlueter and Contributors
|
||||
|
||||
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.
|
@ -0,0 +1,79 @@
|
||||
# once
|
||||
|
||||
Only call a function once.
|
||||
|
||||
## usage
|
||||
|
||||
```javascript
|
||||
var once = require('once')
|
||||
|
||||
function load (file, cb) {
|
||||
cb = once(cb)
|
||||
loader.load('file')
|
||||
loader.once('load', cb)
|
||||
loader.once('error', cb)
|
||||
}
|
||||
```
|
||||
|
||||
Or add to the Function.prototype in a responsible way:
|
||||
|
||||
```javascript
|
||||
// only has to be done once
|
||||
require('once').proto()
|
||||
|
||||
function load (file, cb) {
|
||||
cb = cb.once()
|
||||
loader.load('file')
|
||||
loader.once('load', cb)
|
||||
loader.once('error', cb)
|
||||
}
|
||||
```
|
||||
|
||||
Ironically, the prototype feature makes this module twice as
|
||||
complicated as necessary.
|
||||
|
||||
To check whether you function has been called, use `fn.called`. Once the
|
||||
function is called for the first time the return value of the original
|
||||
function is saved in `fn.value` and subsequent calls will continue to
|
||||
return this value.
|
||||
|
||||
```javascript
|
||||
var once = require('once')
|
||||
|
||||
function load (cb) {
|
||||
cb = once(cb)
|
||||
var stream = createStream()
|
||||
stream.once('data', cb)
|
||||
stream.once('end', function () {
|
||||
if (!cb.called) cb(new Error('not found'))
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
## `once.strict(func)`
|
||||
|
||||
Throw an error if the function is called twice.
|
||||
|
||||
Some functions are expected to be called only once. Using `once` for them would
|
||||
potentially hide logical errors.
|
||||
|
||||
In the example below, the `greet` function has to call the callback only once:
|
||||
|
||||
```javascript
|
||||
function greet (name, cb) {
|
||||
// return is missing from the if statement
|
||||
// when no name is passed, the callback is called twice
|
||||
if (!name) cb('Hello anonymous')
|
||||
cb('Hello ' + name)
|
||||
}
|
||||
|
||||
function log (msg) {
|
||||
console.log(msg)
|
||||
}
|
||||
|
||||
// this will print 'Hello anonymous' but the logical error will be missed
|
||||
greet(null, once(msg))
|
||||
|
||||
// once.strict will print 'Hello anonymous' and throw an error when the callback will be called the second time
|
||||
greet(null, once.strict(msg))
|
||||
```
|
@ -0,0 +1,42 @@
|
||||
var wrappy = require('wrappy')
|
||||
module.exports = wrappy(once)
|
||||
module.exports.strict = wrappy(onceStrict)
|
||||
|
||||
once.proto = once(function () {
|
||||
Object.defineProperty(Function.prototype, 'once', {
|
||||
value: function () {
|
||||
return once(this)
|
||||
},
|
||||
configurable: true
|
||||
})
|
||||
|
||||
Object.defineProperty(Function.prototype, 'onceStrict', {
|
||||
value: function () {
|
||||
return onceStrict(this)
|
||||
},
|
||||
configurable: true
|
||||
})
|
||||
})
|
||||
|
||||
function once (fn) {
|
||||
var f = function () {
|
||||
if (f.called) return f.value
|
||||
f.called = true
|
||||
return f.value = fn.apply(this, arguments)
|
||||
}
|
||||
f.called = false
|
||||
return f
|
||||
}
|
||||
|
||||
function onceStrict (fn) {
|
||||
var f = function () {
|
||||
if (f.called)
|
||||
throw new Error(f.onceError)
|
||||
f.called = true
|
||||
return f.value = fn.apply(this, arguments)
|
||||
}
|
||||
var name = fn.name || 'Function wrapped with `once`'
|
||||
f.onceError = name + " shouldn't be called more than once"
|
||||
f.called = false
|
||||
return f
|
||||
}
|
@ -0,0 +1,67 @@
|
||||
{
|
||||
"_from": "once@^1.3.0",
|
||||
"_id": "once@1.4.0",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=",
|
||||
"_location": "/once",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "once@^1.3.0",
|
||||
"name": "once",
|
||||
"escapedName": "once",
|
||||
"rawSpec": "^1.3.0",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "^1.3.0"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/glob",
|
||||
"/inflight"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
|
||||
"_shasum": "583b1aa775961d4b113ac17d9c50baef9dd76bd1",
|
||||
"_spec": "once@^1.3.0",
|
||||
"_where": "/Users/paolo/Desktop/multiplayer games/likelike-online/node_modules/glob",
|
||||
"author": {
|
||||
"name": "Isaac Z. Schlueter",
|
||||
"email": "i@izs.me",
|
||||
"url": "http://blog.izs.me/"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/isaacs/once/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"dependencies": {
|
||||
"wrappy": "1"
|
||||
},
|
||||
"deprecated": false,
|
||||
"description": "Run a function exactly one time",
|
||||
"devDependencies": {
|
||||
"tap": "^7.0.1"
|
||||
},
|
||||
"directories": {
|
||||
"test": "test"
|
||||
},
|
||||
"files": [
|
||||
"once.js"
|
||||
],
|
||||
"homepage": "https://github.com/isaacs/once#readme",
|
||||
"keywords": [
|
||||
"once",
|
||||
"function",
|
||||
"one",
|
||||
"single"
|
||||
],
|
||||
"license": "ISC",
|
||||
"main": "once.js",
|
||||
"name": "once",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/isaacs/once.git"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "tap test/*.js"
|
||||
},
|
||||
"version": "1.4.0"
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
'use strict';
|
||||
|
||||
function posix(path) {
|
||||
return path.charAt(0) === '/';
|
||||
}
|
||||
|
||||
function win32(path) {
|
||||
// https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
|
||||
var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
|
||||
var result = splitDeviceRe.exec(path);
|
||||
var device = result[1] || '';
|
||||
var isUnc = Boolean(device && device.charAt(1) !== ':');
|
||||
|
||||
// UNC paths are always absolute
|
||||
return Boolean(result[2] || isUnc);
|
||||
}
|
||||
|
||||
module.exports = process.platform === 'win32' ? win32 : posix;
|
||||
module.exports.posix = posix;
|
||||
module.exports.win32 = win32;
|
@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
@ -0,0 +1,75 @@
|
||||
{
|
||||
"_from": "path-is-absolute@^1.0.0",
|
||||
"_id": "path-is-absolute@1.0.1",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=",
|
||||
"_location": "/path-is-absolute",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "path-is-absolute@^1.0.0",
|
||||
"name": "path-is-absolute",
|
||||
"escapedName": "path-is-absolute",
|
||||
"rawSpec": "^1.0.0",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "^1.0.0"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/glob"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
|
||||
"_shasum": "174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f",
|
||||
"_spec": "path-is-absolute@^1.0.0",
|
||||
"_where": "/Users/paolo/Desktop/multiplayer games/likelike-online/node_modules/glob",
|
||||
"author": {
|
||||
"name": "Sindre Sorhus",
|
||||
"email": "sindresorhus@gmail.com",
|
||||
"url": "sindresorhus.com"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/sindresorhus/path-is-absolute/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"deprecated": false,
|
||||
"description": "Node.js 0.12 path.isAbsolute() ponyfill",
|
||||
"devDependencies": {
|
||||
"xo": "^0.16.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
},
|
||||
"files": [
|
||||
"index.js"
|
||||
],
|
||||
"homepage": "https://github.com/sindresorhus/path-is-absolute#readme",
|
||||
"keywords": [
|
||||
"path",
|
||||
"paths",
|
||||
"file",
|
||||
"dir",
|
||||
"absolute",
|
||||
"isabsolute",
|
||||
"is-absolute",
|
||||
"built-in",
|
||||
"util",
|
||||
"utils",
|
||||
"core",
|
||||
"ponyfill",
|
||||
"polyfill",
|
||||
"shim",
|
||||
"is",
|
||||
"detect",
|
||||
"check"
|
||||
],
|
||||
"license": "MIT",
|
||||
"name": "path-is-absolute",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/sindresorhus/path-is-absolute.git"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "xo && node test.js"
|
||||
},
|
||||
"version": "1.0.1"
|
||||
}
|
@ -0,0 +1,59 @@
|
||||
# path-is-absolute [![Build Status](https://travis-ci.org/sindresorhus/path-is-absolute.svg?branch=master)](https://travis-ci.org/sindresorhus/path-is-absolute)
|
||||
|
||||
> Node.js 0.12 [`path.isAbsolute()`](http://nodejs.org/api/path.html#path_path_isabsolute_path) [ponyfill](https://ponyfill.com)
|
||||
|
||||
|
||||
## Install
|
||||
|
||||
```
|
||||
$ npm install --save path-is-absolute
|
||||
```
|
||||
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
const pathIsAbsolute = require('path-is-absolute');
|
||||
|
||||
// Running on Linux
|
||||
pathIsAbsolute('/home/foo');
|
||||
//=> true
|
||||
pathIsAbsolute('C:/Users/foo');
|
||||
//=> false
|
||||
|
||||
// Running on Windows
|
||||
pathIsAbsolute('C:/Users/foo');
|
||||
//=> true
|
||||
pathIsAbsolute('/home/foo');
|
||||
//=> false
|
||||
|
||||
// Running on any OS
|
||||
pathIsAbsolute.posix('/home/foo');
|
||||
//=> true
|
||||
pathIsAbsolute.posix('C:/Users/foo');
|
||||
//=> false
|
||||
pathIsAbsolute.win32('C:/Users/foo');
|
||||
//=> true
|
||||
pathIsAbsolute.win32('/home/foo');
|
||||
//=> false
|
||||
```
|
||||
|
||||
|
||||
## API
|
||||
|
||||
See the [`path.isAbsolute()` docs](http://nodejs.org/api/path.html#path_path_isabsolute_path).
|
||||
|
||||
### pathIsAbsolute(path)
|
||||
|
||||
### pathIsAbsolute.posix(path)
|
||||
|
||||
POSIX specific version.
|
||||
|
||||
### pathIsAbsolute.win32(path)
|
||||
|
||||
Windows specific version.
|
||||
|
||||
|
||||
## License
|
||||
|
||||
MIT © [Sindre Sorhus](https://sindresorhus.com)
|
@ -0,0 +1,675 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||
|
@ -0,0 +1,84 @@
|
||||
[![Build Status](https://travis-ci.org/dhowe/RiTaJS.svg?branch=master)](https://travis-ci.org/dhowe/RiTaJS) <a href="http://www.gnu.org/licenses/gpl-3.0.en.html"><img src="https://img.shields.io/badge/license-GPL-orange.svg" alt="npm version"></a> <img src="https://img.shields.io/npm/dt/rita.svg" alt="npm version">
|
||||
|
||||
|
||||
## RiTa: a generative language toolkit for JavaScript
|
||||
|
||||
<a href="http://rednoise.org/rita"><img height="80" src="http://rednoise.org/rita/img/RiTa-logo3.png"/></a>
|
||||
|
||||
### [The RiTa website](http://rednoise.org/rita)
|
||||
|
||||
RiTa is designed to be an easy-to-use toolkit for experiments in natural language and generative literature. It is implemented in Java and JavaScript (with a common API for both). It is free/libre and open-source via the GPL license.
|
||||
|
||||
About the project
|
||||
--------
|
||||
* Author: [Daniel C. Howe](http://rednoise.org/daniel)
|
||||
* License: GPL (see included [LICENSE](https://github.com/dhowe/RiTaJS/blob/master/LICENSE) file for full license)
|
||||
* Web Site: [https://rednoise.org/rita](http://rednoise.org/rita)
|
||||
* Github Repo: [https://github.com/dhowe/RiTaJS](https://github.com/dhowe/RiTa)
|
||||
* Issues: [https://github.com/dhowe/RiTa/issues](https://github.com/dhowe/RiTa/issues)
|
||||
* Reference: [https://rednoise.org/rita/reference](http://rednoise.org/rita/reference)
|
||||
* FAQ: https://github.com/dhowe/RiTa/wiki
|
||||
* Related: [RiTa](https://github.com/dhowe/RiTa) (Java)
|
||||
|
||||
In [node.js](http://nodejs.org/)
|
||||
--------
|
||||
To install, do the following from a terminal prompt
|
||||
|
||||
`$ npm install rita`
|
||||
|
||||
then use require() from your code
|
||||
|
||||
```javascript
|
||||
var rita = require('rita');
|
||||
var rs = rita.RiString("The elephant took a bite!");
|
||||
console.log(rs.features());
|
||||
```
|
||||
|
||||
To run tests, do the following from a terminal prompt:
|
||||
|
||||
```bash
|
||||
$ cd node_modules/rita && npm install && npm test
|
||||
```
|
||||
|
||||
Or, see the 'Development Setup' instructions below...
|
||||
|
||||
#### Can I contribute?
|
||||
--------
|
||||
Please! We are looking for more coders to help out... Just press *Fork* at the top of this github page and get started, or follow the instructions below...
|
||||
|
||||
#### Development Setup
|
||||
--------
|
||||
- Download and install [git](https://www.git-scm.com/), [npm](https://www.npmjs.org/), and [gulp](). If you have them already, move on to step #2.
|
||||
|
||||
a. You can find a version of __git__ for your OS [here](https://www.git-scm.com/)
|
||||
b. The easiest way to install __npm__ is to install [node.js](http://nodejs.org/)
|
||||
c. You can install __gulp__ via npm as follows:
|
||||
|
||||
```bash
|
||||
$ npm install -g gulp
|
||||
```
|
||||
- [Fork and clone](https://help.github.com/articles/fork-a-repo) this library.
|
||||
|
||||
a. First, login to github and fork the project
|
||||
b. Then, from a terminal/shell:
|
||||
|
||||
```bash
|
||||
$ git clone https://github.com/dhowe/RiTaJS.git
|
||||
```
|
||||
|
||||
- Now navigate into the project folder and install dependencies via npm.
|
||||
```bash
|
||||
$ cd RiTaJS && npm install
|
||||
```
|
||||
|
||||
- To create the library from src, use gulp.
|
||||
```bash
|
||||
$ gulp build
|
||||
```
|
||||
|
||||
- Optionally run tests in node with gulp.
|
||||
```bash
|
||||
$ gulp test
|
||||
```
|
||||
|
||||
- Work on an existing [issue](https://github.com/dhowe/RiTa/issues?q=is%3Aopen+is%3Aissue+label%3ARiTaJS), then [submit a pull request...](https://help.github.com/articles/creating-a-pull-request)
|
@ -0,0 +1,398 @@
|
||||
|
||||
/**
|
||||
* USAGE:
|
||||
* gulp (build | lint | watch | clean | help )
|
||||
* gulp test # test all
|
||||
* gulp test --name RiString # test one
|
||||
*/
|
||||
|
||||
var del = require('del'),
|
||||
gulp = require('gulp'),
|
||||
chmod = require('gulp-chmod'),
|
||||
gulpif = require('gulp-if'),
|
||||
argv = require('yargs').argv,
|
||||
concat = require('gulp-concat'),
|
||||
size = require('gulp-size'),
|
||||
uglify = require('gulp-uglify'),
|
||||
replace = require('gulp-replace'),
|
||||
jshint = require('gulp-jshint'),
|
||||
tasks = require('gulp-task-listing'),
|
||||
sourcemaps = require('gulp-sourcemaps'),
|
||||
pjson = require('./package.json'),
|
||||
rename = require('gulp-rename'),
|
||||
chmod = require('gulp-chmod'),
|
||||
exec = require('child_process').exec,
|
||||
version = pjson.version;
|
||||
|
||||
var testDir = 'test',
|
||||
destDir = 'dist',
|
||||
npm = 'npm',
|
||||
nodeDir = destDir+'/node/rita',
|
||||
tmpDir = '/tmp',
|
||||
srcDir = 'src',
|
||||
rita = 'rita',
|
||||
testFile = 'rita',
|
||||
minimize = false,
|
||||
sourceMaps = false;
|
||||
|
||||
// create a pkg in tmpDir then run 'npm test' on it
|
||||
gulp.task('test-npm-test', ['npm.build'], function(done) {
|
||||
var tgz = 'rita-'+version+'.tgz';
|
||||
var cmd = 'cp '+tgz+' '+tmpDir+' && cd '+tmpDir+' && npm install '+tgz+' &&';
|
||||
cmd += ' cd node_modules/rita && npm install && npm test';
|
||||
exec(cmd, function (err, stdout, stderr) {
|
||||
log("Running 'npm test' on "+tgz);
|
||||
stderr && console.error(stderr);
|
||||
done(err);
|
||||
});
|
||||
});
|
||||
|
||||
// do npm pack on whatever is already in the dist dir
|
||||
gulp.task('npm.build', ['setup-npm'], function(done) {
|
||||
exec(npm + ' pack '+nodeDir, function (err, stdout, stderr) {
|
||||
log("Packing "+nodeDir+'/'+stdout);
|
||||
stderr && console.error(stderr);
|
||||
del(destDir+'/node'); // remove the build dir
|
||||
done(err);
|
||||
});
|
||||
});
|
||||
|
||||
// do npm publish on already created .tgz file
|
||||
gulp.task('npm.publish', [], function(done) {
|
||||
var tgz = 'rita-'+version+'.tgz';
|
||||
exec(npm + ' publish '+tgz, function (err, stdout, stderr) {
|
||||
log("Publishing "+tgz, stdout);
|
||||
stderr && console.error(stderr);
|
||||
done(err);
|
||||
});
|
||||
});
|
||||
|
||||
// build everything, then do npm pack
|
||||
gulp.task('make.lib', [ 'build.full' ], function(done) {
|
||||
gulp.start('npm.build');
|
||||
});
|
||||
|
||||
gulp.task('setup-npm', ['clean-npm', 'build-minify'], function(done) {
|
||||
|
||||
// copy in the node readme
|
||||
gulp.src('README.node.md')
|
||||
.pipe(rename('README.md'))
|
||||
.pipe(gulp.dest(nodeDir));
|
||||
|
||||
// copy in other loose files
|
||||
gulp.src(['./LICENSE', './package.json', './gulpfile.js', 'examples/tonic.js'])
|
||||
.pipe(gulp.dest(nodeDir));
|
||||
|
||||
// copy in the tests
|
||||
gulp.src(testFiles(true))
|
||||
.pipe(gulp.dest(nodeDir + '/test'));
|
||||
|
||||
// copy in the tests
|
||||
gulp.src(testDir + '/html/data/*')
|
||||
.pipe(gulp.dest(nodeDir + '/test/html/data/'));
|
||||
|
||||
// copy in the (default) code
|
||||
gulp.src(destDir + '/rita-full.min.js')
|
||||
.pipe(rename('rita.js'))
|
||||
.pipe(gulp.dest(nodeDir + '/lib'));
|
||||
|
||||
// copy in the (core-only) code
|
||||
gulp.src(destDir + '/rita-small.min.js')
|
||||
.pipe(rename('rita-tiny.js'))
|
||||
.pipe(gulp.dest(nodeDir + '/lib'));
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
// list all the defined tasks
|
||||
gulp.task('help', tasks);
|
||||
|
||||
// clean out the build-dir
|
||||
gulp.task('clean', function(f) { del(destDir, f); });
|
||||
|
||||
gulp.task('clean-npm', function(f) { del(nodeDir, f); });
|
||||
|
||||
// run lint on the non-uglified output (no lexicon)
|
||||
gulp.task('lint', ['build'], function() {
|
||||
|
||||
log('Linting '+destDir+'/rita.js');
|
||||
|
||||
return gulp.src(destDir+'/rita.js')
|
||||
.pipe(jshint({ expr: 1, laxbreak: 1 }))
|
||||
.pipe(jshint.reporter('default'));
|
||||
});
|
||||
|
||||
// run lint on the non-uglified output (with lexicon)
|
||||
gulp.task('lint.full', ['build'], function() {
|
||||
|
||||
log('Linting '+destDir+'/rita-full.js');
|
||||
|
||||
return gulp.src(destDir+'/rita-full.js')
|
||||
.pipe(jshint({ expr: 1, laxbreak: 1 }))
|
||||
.pipe(jshint.reporter('default'));
|
||||
});
|
||||
|
||||
// watch the src-dir for changes, then build
|
||||
gulp.task('watch.full', ['build.full'], function() {
|
||||
|
||||
log('Watching ' + srcDir + '/*.js');
|
||||
gulp.watch(srcDir + '/*.js', [ 'build.full' ]);
|
||||
});
|
||||
|
||||
gulp.task('watch', [ 'build' ], function() {
|
||||
|
||||
log('Watching ' + srcDir + '/*.js');
|
||||
gulp.watch(srcDir + '/*.js', [ 'build' ]);
|
||||
});
|
||||
|
||||
// concatenate sources to 'dist' folder
|
||||
gulp.task('build-lex', ['clean'], function() {
|
||||
|
||||
return gulp.src(sourceFiles("full"))
|
||||
.pipe(replace('##version##', version))
|
||||
.pipe(concat(rita+'-full.js'))
|
||||
.pipe(size({showFiles:true}))
|
||||
.pipe(chmod(644))
|
||||
.pipe(gulp.dest(destDir));
|
||||
});
|
||||
|
||||
gulp.task('build-novb', function() {
|
||||
|
||||
return gulp.src(sourceFiles("novb"))
|
||||
.pipe(replace('##version##', version))
|
||||
.pipe(concat(rita+'-novb.js'))
|
||||
.pipe(size({showFiles:true}))
|
||||
.pipe(chmod(644))
|
||||
.pipe(gulp.dest(destDir));
|
||||
});
|
||||
|
||||
gulp.task('build-1000-lex', ['clean'], function() {
|
||||
|
||||
return gulp.src(sourceFiles("medium"))
|
||||
.pipe(replace('##version##', version))
|
||||
.pipe(concat(rita+'-small.js'))
|
||||
.pipe(size({showFiles:true}))
|
||||
.pipe(chmod(644))
|
||||
.pipe(gulp.dest(destDir));
|
||||
});
|
||||
|
||||
gulp.task('build-nolex', [ 'clean' ], function() {
|
||||
|
||||
return gulp.src(sourceFiles(false))
|
||||
.pipe(replace('##version##', version))
|
||||
.pipe(concat(rita+'.js'))
|
||||
.pipe(size({showFiles:true}))
|
||||
.pipe(chmod(644))
|
||||
.pipe(gulp.dest(destDir));
|
||||
});
|
||||
|
||||
// concatenate/minify sources to 'dist' folder
|
||||
|
||||
gulp.task('build-medium', ['clean'], function() {
|
||||
|
||||
return gulp.src(sourceFiles("medium"))
|
||||
.pipe(replace('##version##', version))
|
||||
.pipe(concat(rita+'-medium.js'))
|
||||
.pipe(size({showFiles:true}))
|
||||
.pipe(chmod(644))
|
||||
.pipe(gulp.dest(destDir));
|
||||
});
|
||||
|
||||
gulp.task('build-small', ['clean'], function() {
|
||||
|
||||
return gulp.src(sourceFiles("small"))
|
||||
.pipe(replace('##version##', version))
|
||||
.pipe(concat(rita+'-small.js'))
|
||||
.pipe(size({showFiles:true}))
|
||||
.pipe(chmod(644))
|
||||
.pipe(gulp.dest(destDir));
|
||||
});
|
||||
|
||||
gulp.task('build-tiny', ['clean'], function() {
|
||||
|
||||
return gulp.src(sourceFiles("tiny"))
|
||||
.pipe(replace('##version##', version))
|
||||
.pipe(concat(rita+'-tiny.js'))
|
||||
.pipe(size({showFiles:true}))
|
||||
.pipe(chmod(644))
|
||||
.pipe(gulp.dest(destDir));
|
||||
});
|
||||
|
||||
|
||||
gulp.task('build-minify-lex', [ 'build-lex' ], function() {
|
||||
|
||||
return gulp.src(destDir+'/'+rita+'-full.js')
|
||||
.pipe(gulpif(sourceMaps, sourcemaps.init()))
|
||||
.pipe(uglify())
|
||||
.pipe(gulpif(sourceMaps, sourcemaps.write('./')))
|
||||
.pipe(rename(rita+'-full.min.js'))
|
||||
.pipe(size({showFiles:true}))
|
||||
.pipe(chmod(644))
|
||||
.pipe(gulp.dest(destDir));
|
||||
});
|
||||
|
||||
// concatenate/minify sources to 'dist' folder
|
||||
gulp.task('build-minify-1000-lex', [ 'build-1000-lex' ], function() {
|
||||
|
||||
return gulp.src(destDir+'/'+rita+'-small.js')
|
||||
.pipe(gulpif(sourceMaps, sourcemaps.init()))
|
||||
.pipe(uglify())
|
||||
.pipe(gulpif(sourceMaps, sourcemaps.write('./')))
|
||||
.pipe(rename(rita+'-small.min.js'))
|
||||
.pipe(size({showFiles:true}))
|
||||
.pipe(chmod(644))
|
||||
.pipe(gulp.dest(destDir));
|
||||
});
|
||||
|
||||
gulp.task('build-minify-nolex', [ 'build-nolex' ], function() {
|
||||
|
||||
return gulp.src(destDir+'/'+rita+'.js')
|
||||
.pipe(gulpif(sourceMaps, sourcemaps.init()))
|
||||
.pipe(uglify())
|
||||
.pipe(gulpif(sourceMaps, sourcemaps.write('./')))
|
||||
.pipe(rename(rita+'.min.js'))
|
||||
.pipe(size({showFiles:true}))
|
||||
.pipe(chmod(644))
|
||||
.pipe(gulp.dest(destDir));
|
||||
});
|
||||
|
||||
|
||||
// runs tests without loading lexicon
|
||||
// usage: gulp test
|
||||
// gulp test --name RiString
|
||||
gulp.task('test.quick', [ 'build' ], function() {
|
||||
|
||||
destDir = 'dist';
|
||||
testFile = 'rita';
|
||||
tests = testFiles(true);
|
||||
|
||||
return gulp.start('test-only');
|
||||
});
|
||||
|
||||
// do tests after npm install (same as test, but runs on 'lib')
|
||||
gulp.task('test-npm', [ 'build' ], function() {
|
||||
|
||||
destDir = 'lib';
|
||||
testFile = 'rita';
|
||||
tests = testFiles(true);
|
||||
|
||||
return gulp.start('test-only');
|
||||
});
|
||||
|
||||
// runs tests with lexicon loaded
|
||||
// usage: gulp test
|
||||
// gulp test --name RiString
|
||||
gulp.task('test', [ 'build' ], function (done) {
|
||||
|
||||
destDir = 'dist';
|
||||
testFile = 'rita-full';
|
||||
tests = testFiles(false);
|
||||
|
||||
return gulp.start('test-only');
|
||||
});
|
||||
|
||||
// runs tests without building first
|
||||
gulp.task('test-only', function (done) {
|
||||
|
||||
var testrunner = require("qunit");
|
||||
|
||||
if (argv.name) {
|
||||
if (argv.name === 'RiLexicon' || argv.name ==='SimilarBySound') // tmp
|
||||
testFile = 'rita-full'
|
||||
tests = [ testDir + '/' + argv.name + '-tests.js' ];
|
||||
log('Testing: ' + tests[0]);
|
||||
}
|
||||
|
||||
testrunner.setup({
|
||||
maxBlockDuration: 20000,
|
||||
log: {
|
||||
globalSummary: true,
|
||||
errors: true
|
||||
}
|
||||
});
|
||||
|
||||
var testSrc = destDir + '/' + testFile + '.js';
|
||||
log('Source: ' + testSrc);
|
||||
|
||||
testrunner.run({
|
||||
deps: [ testDir + '/qunit-helpers.js' ],
|
||||
code: testSrc,
|
||||
tests: tests
|
||||
},
|
||||
function (err, report) {
|
||||
if (err) {
|
||||
console.error(err);
|
||||
console.error(report);
|
||||
process.exit(1);
|
||||
}
|
||||
testFile = 'rita' // restore
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
// Helper functions --------------------------------------
|
||||
|
||||
function testFiles(skipRiLexicon) {
|
||||
|
||||
var tests = [
|
||||
testDir + '/qunit-helpers.js',
|
||||
testDir + '/LibStructure-tests.js',
|
||||
//testDir + '/RiTaEvent-tests.js',
|
||||
testDir + '/RiString-tests.js',
|
||||
testDir + '/RiTa-tests.js',
|
||||
testDir + '/RiGrammar-tests.js',
|
||||
testDir + '/RiMarkov-tests.js',
|
||||
testDir + '/UrlLoading-tests.js'
|
||||
];
|
||||
|
||||
if (!skipRiLexicon) {
|
||||
tests.push(testDir + '/RiLexicon-tests.js');
|
||||
}
|
||||
|
||||
return tests;
|
||||
}
|
||||
|
||||
function sourceFiles(lexStatus) {
|
||||
|
||||
var src = [ srcDir + '/header.js', srcDir + '/rita.js' ];
|
||||
|
||||
if (lexStatus === "full") {
|
||||
src.push(srcDir + '/rita_lts.js');
|
||||
src.push(srcDir + '/rita_dict.js');
|
||||
//src.push(srcDir + '/rilexicon.js');
|
||||
}
|
||||
else if ( lexStatus === "medium") {
|
||||
src.push(srcDir + '/rita_dict_1000.js');
|
||||
src.push(srcDir + '/rita_lts.js');
|
||||
// src.push(srcDir + '/rilexicon.js');
|
||||
}
|
||||
else if ( lexStatus === "small") {
|
||||
src.push(srcDir + '/rita_dict_1000.js');
|
||||
//src.push(srcDir + '/rilexicon.js');
|
||||
}
|
||||
else if (lexStatus === "novb") {
|
||||
src.push(srcDir + '/rita_lts.js');
|
||||
src.push(srcDir + '/rita_dict_novb.js');
|
||||
//src.push(srcDir + '/rilexicon.js');
|
||||
}
|
||||
//tiny only rita.js
|
||||
|
||||
src.push(srcDir + '/footer.js');
|
||||
|
||||
//console.log(src);
|
||||
return src;
|
||||
}
|
||||
|
||||
function log(msg) { console.log('[INFO] '+ msg); }
|
||||
|
||||
// ----------------------------------------------------
|
||||
|
||||
// task composition
|
||||
gulp.task('build', [ 'build-lex', 'build-1000-lex','build-nolex']);
|
||||
gulp.task('make-sizes', [ 'build-lex', 'build-medium','build-small','build-tiny']);
|
||||
gulp.task('build.full', [ 'build', 'build-minify' ]);
|
||||
gulp.task('build-minify', [ 'build-minify-1000-lex', 'build-minify-lex','build-minify-nolex' ]);
|
||||
|
||||
// help is the default task
|
||||
gulp.task('default', [ 'help' ]);
|
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -0,0 +1,84 @@
|
||||
{
|
||||
"_from": "rita",
|
||||
"_id": "rita@1.3.94",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha512-/E8foRjE+uCZpe35pt1BlyYnWnLB/sw1BN711paLYLl+ebU8k0AXwteKwJlqviyrFlItGtGJOuc6mUMuIUELvQ==",
|
||||
"_location": "/rita",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "tag",
|
||||
"registry": true,
|
||||
"raw": "rita",
|
||||
"name": "rita",
|
||||
"escapedName": "rita",
|
||||
"rawSpec": "",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "latest"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"#USER",
|
||||
"/"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/rita/-/rita-1.3.94.tgz",
|
||||
"_shasum": "712cc04fe639e3d5be205a7096fe5dd3037ce8c3",
|
||||
"_spec": "rita",
|
||||
"_where": "/Users/paolo/Desktop/multiplayer games/likelike-online",
|
||||
"author": {
|
||||
"name": "Daniel C. Howe",
|
||||
"email": "daniel@rednoise.org"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/dhowe/RiTa/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"dependencies": {
|
||||
"yamljs": "^0.2.10"
|
||||
},
|
||||
"deprecated": false,
|
||||
"description": "RiTa: A toolkit for natural language and computational literature",
|
||||
"devDependencies": {
|
||||
"argv": "0.0.2",
|
||||
"del": "^1.2.0",
|
||||
"gulp": "^3.9.1",
|
||||
"gulp-chmod": "^1.3.0",
|
||||
"gulp-concat": "^2.6.0",
|
||||
"gulp-if": "^2.0.2",
|
||||
"gulp-jshint": "^2.1.0",
|
||||
"gulp-rename": "^1.2.2",
|
||||
"gulp-replace": "^0.5.4",
|
||||
"gulp-size": "^2.0.0",
|
||||
"gulp-sourcemaps": "^1.5.2",
|
||||
"gulp-task-listing": "^1.0.1",
|
||||
"gulp-uglify": "^1.4.0",
|
||||
"gulp-util": "^3.0.6",
|
||||
"jshint": "^2.9.7",
|
||||
"qunit": "^0.7.5",
|
||||
"yargs": "^3.15.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
},
|
||||
"homepage": "https://rednoise.org/rita",
|
||||
"keywords": [
|
||||
"nlp",
|
||||
"natural language",
|
||||
"language",
|
||||
"writing",
|
||||
"generative"
|
||||
],
|
||||
"license": "GPL-3.0",
|
||||
"main": "lib/rita.js",
|
||||
"name": "rita",
|
||||
"optionalDependencies": {
|
||||
"yamljs": "^0.2.10"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/dhowe/RiTa.git"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "gulp test-npm"
|
||||
},
|
||||
"tonicExampleFilename": "tonic.js",
|
||||
"version": "1.3.94"
|
||||
}
|
@ -0,0 +1,162 @@
|
||||
/*global console, test, throws, equal, notEqual, expect, require, ok,
|
||||
QUnit, RiTa, RiTaEvent, RiString, RiGrammar, RiMarkov, RiLexicon */
|
||||
|
||||
var runtests = function() {
|
||||
|
||||
QUnit.module("LibraryStructure", {
|
||||
setup: function() {},
|
||||
teardown: function() {}
|
||||
});
|
||||
|
||||
test("Public Objects", function() {
|
||||
|
||||
ok(typeof RiTa != 'undefined');
|
||||
ok(typeof RiString != 'undefined');
|
||||
ok(typeof RiLexicon != 'undefined');
|
||||
ok(typeof RiGrammar != 'undefined');
|
||||
ok(typeof RiMarkov != 'undefined');
|
||||
ok(typeof RiWordNet != 'undefined');
|
||||
if (typeof window != 'undefined' && window) {
|
||||
ok(typeof RiText != 'undefined');
|
||||
}
|
||||
});
|
||||
|
||||
test("Private Statics (funs)", function() {
|
||||
|
||||
if (typeof window != 'undefined' && window) {
|
||||
// fails in phantom outside the conditional ??
|
||||
equal(typeof is, 'undefined');
|
||||
}
|
||||
equal(typeof _wordOffsetFor, 'undefined');
|
||||
equal(typeof _handleLeading, 'undefined');
|
||||
equal(typeof _disposeOne, 'undefined');
|
||||
});
|
||||
|
||||
test("Private Statics (vars)", function() {
|
||||
|
||||
equal(typeof _VERSION_, 'undefined');
|
||||
equal(typeof RiTa._VERSION_, 'undefined');
|
||||
equal(typeof timers, 'undefined');
|
||||
equal(typeof RiTa.timers, 'undefined');
|
||||
});
|
||||
|
||||
test("Member Functions", function() {
|
||||
|
||||
var rx = new RiString("hello");
|
||||
equal(typeof rx.charAt, 'function');
|
||||
var rs = RiString("hello");
|
||||
equal(typeof rs.charAt, 'function');
|
||||
var rg = RiMarkov(3);
|
||||
equal(typeof rg.loadTokens, 'function');
|
||||
rg = new RiMarkov(2);
|
||||
equal(typeof rg.loadTokens, 'function');
|
||||
var rl = new RiLexicon();
|
||||
equal(typeof rl.containsWord, 'function');
|
||||
});
|
||||
|
||||
test("Member Variables", function() {
|
||||
|
||||
ok(RiString("x").text);
|
||||
ok(new RiString("x").text);
|
||||
ok(RiGrammar()._rules);
|
||||
ok(new RiGrammar()._rules);
|
||||
});
|
||||
|
||||
test("Public Statics", function() {
|
||||
|
||||
equal(typeof RiTa.splitSentences, 'function');
|
||||
equal(typeof RiTa.getPhonemes, 'function');
|
||||
equal(typeof RiTa.random, 'function');
|
||||
equal(typeof RiTa.containsWord, 'function');
|
||||
});
|
||||
|
||||
test("Public Constants", function() {
|
||||
|
||||
ok(RiTa.VERSION);
|
||||
ok(RiTa.PRESENT_TENSE);
|
||||
ok(RiTa.SECOND_PERSON);
|
||||
ok(RiGrammar.START_RULE);
|
||||
});
|
||||
|
||||
test("Internal Classes", function() {
|
||||
|
||||
equal(typeof Type, 'undefined', 'Type is visible!');
|
||||
equal(typeof Timer, 'undefined', 'Timer is visible!');
|
||||
equal(typeof Phones, 'undefined', 'Phones is visible!');
|
||||
equal(typeof Conjugator, 'undefined', 'Conjugator');
|
||||
equal(typeof MinEditDist, 'undefined', 'MinEditDist');
|
||||
equal(typeof PosTagger, 'undefined', 'PosTagger');
|
||||
equal(typeof RegexRule, 'undefined', 'RegexRule');
|
||||
equal(typeof Easing, 'undefined', 'Easing');
|
||||
equal(typeof Interpolation, 'undefined', 'Interpolation');
|
||||
equal(typeof TextBehavior, 'undefined', 'TextBehavior');
|
||||
});
|
||||
|
||||
test("Private Constants", function() {
|
||||
|
||||
equal(typeof SP, 'undefined');
|
||||
equal(typeof A, 'undefined');
|
||||
equal(typeof PLURAL_RULES, 'undefined');
|
||||
equal(typeof QUESTION_STARTS, 'undefined');
|
||||
equal(typeof PAST_PARTICIPLE_RULESET, 'undefined');
|
||||
});
|
||||
|
||||
test("Constructors", function() {
|
||||
|
||||
equal(typeof RiString, 'function'); // pub
|
||||
equal(typeof RiGrammar, 'function');
|
||||
equal(typeof RiLexicon, 'function');
|
||||
|
||||
notEqual(typeof RiTa, 'function'); // prv
|
||||
|
||||
var rx = new RiString("hello");
|
||||
equal(typeof rx, 'object');
|
||||
|
||||
var rs = RiString("hello");
|
||||
equal(typeof rx, 'object');
|
||||
|
||||
var lr = RiGrammar();
|
||||
equal(typeof lr, 'object');
|
||||
|
||||
var lg = new RiGrammar();
|
||||
equal(typeof lg, 'object');
|
||||
|
||||
if (typeof window != 'undefined') {
|
||||
|
||||
equal(typeof RiText, 'function');
|
||||
|
||||
}
|
||||
|
||||
throws(function() {
|
||||
RiTa.SILENT = 1;
|
||||
try {
|
||||
new RiTa();
|
||||
} catch (e) {
|
||||
throw Error("no constructor");
|
||||
}
|
||||
RiTa.SILENT = 0;
|
||||
});
|
||||
|
||||
throws(function() {
|
||||
RiTa.SILENT = 1;
|
||||
try {
|
||||
RiTa();
|
||||
} catch (e) {
|
||||
throw Error("no constructor");
|
||||
}
|
||||
RiTa.SILENT = 0;
|
||||
});
|
||||
});
|
||||
|
||||
test("Private Functions", function() {
|
||||
|
||||
equal(typeof startsWith, 'undefined');
|
||||
equal(typeof isNull, 'undefined');
|
||||
equal(typeof makeClass, 'undefined');
|
||||
equal(typeof handleLeading, 'undefined');
|
||||
equal(typeof disposeOne, 'undefined');
|
||||
});
|
||||
|
||||
};
|
||||
|
||||
if (typeof exports != 'undefined') runtests();
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,491 @@
|
||||
/*global console, test, throws, equal, fail, notEqual, expect, require, ok,
|
||||
QUnit, RiTa, RiString, RiGrammar, RiMarkov, RiLexicon */
|
||||
|
||||
var runtests = function() {
|
||||
|
||||
// only check this for local tests
|
||||
var allowLocalWebServer = typeof process != 'undefined'
|
||||
&& (!process.env.CI && process.env.ALLOW_URL_TESTS);
|
||||
|
||||
RiTa.SILENT = 1;
|
||||
|
||||
var filePath = (typeof module != 'undefined' && module.exports) ? "./test/html/data/" : "./data/"
|
||||
|
||||
QUnit.module("UrlLoading", {
|
||||
|
||||
setup: function() {},
|
||||
teardown: function() {}
|
||||
});
|
||||
|
||||
asyncTest("RiTa.loadString1(file)", function() {
|
||||
|
||||
RiTa.loadString(filePath + "sentence1.json", function(s) {
|
||||
ok(s && s.length > 100);
|
||||
//console.log(s);
|
||||
ok(JSON.parse(s));
|
||||
start();
|
||||
});
|
||||
});
|
||||
|
||||
asyncTest("RiTa.loadString2(file)", function() {
|
||||
|
||||
RiTa.loadString(filePath + "sentence2.json", function(s) {
|
||||
ok(s && s.length > 100);
|
||||
ok(JSON.parse(s));
|
||||
start();
|
||||
});
|
||||
});
|
||||
|
||||
asyncTest("RiTa.loadStrings1(file)", function() {
|
||||
|
||||
RiTa.loadStrings(filePath + "sentence1.json", function(s) {
|
||||
ok(s && s.length > 1);
|
||||
//console.log(s);
|
||||
ok(JSON.parse(s.join('\n')));
|
||||
start();
|
||||
});
|
||||
});
|
||||
|
||||
asyncTest("RiTa.loadStrings2(file)", function() {
|
||||
|
||||
RiTa.loadStrings(filePath + "sentence2.json", function(s) {
|
||||
ok(s && s.length > 1);
|
||||
ok(JSON.parse(s.join('\n')));
|
||||
start();
|
||||
});
|
||||
});
|
||||
|
||||
asyncTest("RiTa.testLoadConcordance", function () { // SLOW
|
||||
|
||||
RiTa.loadString(filePath + "kafka.txt", function (txt) {
|
||||
|
||||
// test with all false
|
||||
var args = {
|
||||
ignoreCase: false,
|
||||
ignorePunctuation: false,
|
||||
ignoreStopWords: false
|
||||
}
|
||||
data = RiTa.concordance(txt, args);
|
||||
ok(data["Gregor"] == 199);
|
||||
ok(data["Gregor"] + data["Gregor's"] == 298);
|
||||
ok(data["sister"] == 96);
|
||||
ok(data["sister"] + data["sister's"] == 101);
|
||||
ok(data["here"] == 19);
|
||||
ok(data["the"] == 1097);
|
||||
ok(data["The"] == 51);
|
||||
ok(data[","] == 1292);
|
||||
ok(data["."] == 737);
|
||||
|
||||
|
||||
// test all true
|
||||
var nUppercaseFather = data["Father"];
|
||||
var nLowercaseFather = data["father"];
|
||||
args.ignoreCase = true;
|
||||
args.ignorePunctuation = true;
|
||||
args.ignoreStopWords = true;
|
||||
data = RiTa.concordance(txt, args);
|
||||
ok(data["gregor"] + data["gregor's"] == 298);
|
||||
ok(data["sister"] + data["sister's"] == 101);
|
||||
equal(data["here"], null);
|
||||
equal(data["the"], null);
|
||||
equal(data[","], null);
|
||||
equal(data["."], null);
|
||||
ok(data["father"] == nUppercaseFather + nLowercaseFather);
|
||||
|
||||
// test ignoreCase
|
||||
args.ignoreCase = true;
|
||||
args.ignorePunctuation = false;
|
||||
args.ignoreStopWords = false;
|
||||
data = RiTa.concordance(txt, args);
|
||||
ok(data["father"] == nUppercaseFather + nLowercaseFather);
|
||||
|
||||
// test ignorePunctuation
|
||||
args.ignoreCase = false;
|
||||
args.ignorePunctuation = true;
|
||||
args.ignoreStopWords = false;
|
||||
data = RiTa.concordance(txt, args);
|
||||
equal(data[","], null);
|
||||
equal(data["."], null);
|
||||
|
||||
// test ignoreStopWords
|
||||
args.ignoreCase = false;
|
||||
args.ignorePunctuation = false;
|
||||
args.ignoreStopWords = true;
|
||||
data = RiTa.concordance(txt, args);
|
||||
equal(data["here"], null);
|
||||
equal(data["the"], null);
|
||||
|
||||
// test ignoreStopWords and ignorePunctuation
|
||||
args.ignoreCase = false;
|
||||
args.ignorePunctuation = true;
|
||||
args.ignoreStopWords = true;
|
||||
data = RiTa.concordance(txt, args);
|
||||
equal(data[","], null);
|
||||
equal(data["."], null);
|
||||
equal(data["here"], null);
|
||||
equal(data["the"], null);
|
||||
|
||||
// test ignoreStopWords and ignoreCase
|
||||
args.ignoreCase = true;
|
||||
args.ignorePunctuation = false;
|
||||
args.ignoreStopWords = true;
|
||||
data = RiTa.concordance(txt, args);
|
||||
ok(data["father"] == nUppercaseFather + nLowercaseFather);
|
||||
equal(data["here"], null);
|
||||
equal(data["the"], null);
|
||||
|
||||
// test ignorePunctuation and ignoreCase
|
||||
args.ignoreCase = true;
|
||||
args.ignorePunctuation = true;
|
||||
args.ignoreStopWords = false;
|
||||
data = RiTa.concordance(txt, args);
|
||||
ok(data["father"] == nUppercaseFather + nLowercaseFather);
|
||||
equal(data[","], null);
|
||||
equal(data["."], null);
|
||||
|
||||
// test wordsToIgnore
|
||||
args.wordsToIgnore = ["father", "sister"];
|
||||
args.ignoreCase = false;
|
||||
args.ignorePunctuation = false;
|
||||
args.ignoreStopWords = false;
|
||||
data = RiTa.concordance(txt, args);
|
||||
equal(data["father"], null);
|
||||
equal(data["sister"], null);
|
||||
|
||||
start();
|
||||
});
|
||||
});
|
||||
|
||||
asyncTest("RiTa.testLoadKwicModel", function () {
|
||||
|
||||
RiTa.loadString(filePath + "kafka.txt", function (txt) {
|
||||
|
||||
var args = {
|
||||
ignoreCase: false,
|
||||
ignorePunctuation: false,
|
||||
ignoreStopWords: false
|
||||
}
|
||||
|
||||
// test ignorePunctuation
|
||||
args.ignorePunctuation = false;
|
||||
lines = RiTa.kwic(txt, ",", args);
|
||||
equal(lines.length, 1091);
|
||||
args.ignorePunctuation = true;
|
||||
lines = RiTa.kwic(txt, ",", args);
|
||||
equal(lines.length, 0);
|
||||
|
||||
// test ignoreCase
|
||||
args.wordCount = 4;
|
||||
args.ignoreCase = true;
|
||||
lines = RiTa.kwic(txt, "eventually", args);
|
||||
equal(lines.length, 2);
|
||||
args.ignoreCase = false;
|
||||
lines = RiTa.kwic(txt, "eventually", args);
|
||||
equal(lines.length, 1);
|
||||
|
||||
// test ignoreStopWords
|
||||
lines = RiTa.kwic(txt, "here", args);
|
||||
equal(lines.length, 19);
|
||||
args.ignoreStopWords = true;
|
||||
lines = RiTa.kwic(txt, "here", args);
|
||||
equal(lines.length, 0);
|
||||
|
||||
// test wordCount
|
||||
args.wordCount = 6;
|
||||
args.ignoreCase = false;
|
||||
lines = RiTa.kwic(txt, "sister", args);
|
||||
for (var i = 0; i < lines.length; i++) {
|
||||
var length = RiTa.tokenize(lines[i]).length;
|
||||
equal(length, 6 + 1 + 6);
|
||||
}
|
||||
|
||||
// test wordsToIgnore
|
||||
args.wordsToIgnore = ["father", "sister"];
|
||||
lines = RiTa.kwic(txt, "father", args);
|
||||
equal(lines.length, 0);
|
||||
lines = RiTa.kwic(txt, "sister", args);
|
||||
equal(lines.length, 0);
|
||||
|
||||
// test against issue #169
|
||||
args.wordCount = 6;
|
||||
lines = RiTa.kwic(txt, "door", args);
|
||||
equal(lines.length, 86);
|
||||
|
||||
start();
|
||||
});
|
||||
});
|
||||
|
||||
// RiGrammar
|
||||
//////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
var sentenceGrammar = {
|
||||
"<start>" : "<noun_phrase> <verb_phrase>.",
|
||||
"<noun_phrase>" : "<determiner> <noun>",
|
||||
"<verb_phrase>" : "<verb> | <verb> <noun_phrase> [0.1]",
|
||||
"<determiner>" : "a [0.1] | the",
|
||||
"<noun>" : "woman | man",
|
||||
"<verb>" : "shoots"
|
||||
};
|
||||
|
||||
var sentenceGrammar2 = {
|
||||
"<start>" : "<noun_phrase> <verb_phrase>.",
|
||||
"<noun_phrase>" : "<determiner> <noun>",
|
||||
"<determiner>" : [ "a [0.1]", "the" ],
|
||||
"<verb_phrase>" : [ "<verb> <noun_phrase> [0.1]", "<verb>" ],
|
||||
"<noun>" : ["woman", "man"],
|
||||
"<verb>" : "shoots"
|
||||
};
|
||||
|
||||
asyncTest("RiGrammar.loadFrom(file)", function() {
|
||||
|
||||
var rg1 = new RiGrammar();
|
||||
rg1.loadFrom(filePath + "sentence1.json");
|
||||
|
||||
var rg2 = RiGrammar(JSON.stringify(sentenceGrammar));
|
||||
var rg3 = RiGrammar(JSON.stringify(sentenceGrammar2));
|
||||
|
||||
var ts = +new Date();
|
||||
var id = setInterval(function() {
|
||||
|
||||
if (rg1.ready()) {
|
||||
|
||||
ok(rg1);
|
||||
deepEqual(rg1, rg2);
|
||||
deepEqual(rg1, rg3);
|
||||
start();
|
||||
clearInterval(id);
|
||||
}
|
||||
else {
|
||||
|
||||
var now = +new Date();
|
||||
if (now - ts > 5000) {
|
||||
equal("no result", 0);
|
||||
start();
|
||||
clearInterval(id);
|
||||
}
|
||||
}
|
||||
|
||||
}, 50);
|
||||
});
|
||||
|
||||
asyncTest("RiGrammar.loadFrom2(file)", function() {
|
||||
|
||||
var rg1 = new RiGrammar();
|
||||
rg1.loadFrom(filePath + "sentence2.json");
|
||||
var rg2 = RiGrammar(JSON.stringify(sentenceGrammar));
|
||||
var rg3 = RiGrammar(JSON.stringify(sentenceGrammar2));
|
||||
|
||||
var ts = +new Date();
|
||||
var id = setInterval(function() {
|
||||
|
||||
if (rg1.ready()) {
|
||||
|
||||
ok(rg1);
|
||||
deepEqual(rg1, rg2);
|
||||
deepEqual(rg1, rg3);
|
||||
start();
|
||||
clearInterval(id);
|
||||
}
|
||||
else {
|
||||
|
||||
var now = +new Date();
|
||||
if (now - ts > 5000) {
|
||||
equal("no result", 0);
|
||||
start();
|
||||
clearInterval(id);
|
||||
}
|
||||
}
|
||||
|
||||
}, 50);
|
||||
});
|
||||
|
||||
asyncTest("RiGrammar.loadFrom3(file)", function() {
|
||||
|
||||
var rg1 = new RiGrammar();
|
||||
rg1.loadFrom(filePath + "sentence1.yaml");
|
||||
|
||||
var rg2 = RiGrammar(JSON.stringify(sentenceGrammar));
|
||||
var rg3 = RiGrammar(JSON.stringify(sentenceGrammar2));
|
||||
|
||||
var ts = +new Date();
|
||||
var id = setInterval(function() {
|
||||
|
||||
if (rg1.ready()) {
|
||||
|
||||
ok(rg1);
|
||||
deepEqual(rg1, rg2);
|
||||
deepEqual(rg1, rg3);
|
||||
start();
|
||||
clearInterval(id);
|
||||
}
|
||||
else {
|
||||
|
||||
var now = +new Date();
|
||||
if (now - ts > 5000) {
|
||||
equal("no result", 0);
|
||||
start();
|
||||
clearInterval(id);
|
||||
}
|
||||
}
|
||||
|
||||
}, 50);
|
||||
});
|
||||
|
||||
asyncTest("RiGrammar.loadFrom4(file)", function() {
|
||||
|
||||
var rg1 = new RiGrammar();
|
||||
rg1.loadFrom(filePath + "sentence2.yaml");
|
||||
var rg2 = RiGrammar(JSON.stringify(sentenceGrammar));
|
||||
var rg3 = RiGrammar(JSON.stringify(sentenceGrammar2));
|
||||
|
||||
var ts = +new Date();
|
||||
var id = setInterval(function() {
|
||||
|
||||
if (rg1.ready()) {
|
||||
|
||||
ok(rg1);
|
||||
deepEqual(rg1, rg2);
|
||||
deepEqual(rg1, rg3);
|
||||
|
||||
start();
|
||||
clearInterval(id);
|
||||
}
|
||||
else {
|
||||
|
||||
var now = +new Date();
|
||||
if (now - ts > 5000) {
|
||||
equal("no result", 0);
|
||||
start();
|
||||
clearInterval(id);
|
||||
}
|
||||
}
|
||||
|
||||
}, 50);
|
||||
});
|
||||
|
||||
// RiMarkov
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
asyncTest("RiMarkov.loadFromFile", function() {
|
||||
|
||||
var rm = new RiMarkov(2);
|
||||
rm.loadFrom(filePath + "kafka.txt");
|
||||
|
||||
var ts = +new Date();
|
||||
var id = setInterval(function() {
|
||||
|
||||
if (rm.ready()) {
|
||||
|
||||
ok(rm.size());
|
||||
// TODO: 1 or 2 more better tests here
|
||||
|
||||
clearInterval(id);
|
||||
start();
|
||||
|
||||
} else {
|
||||
|
||||
//console.log("waiting...");
|
||||
var now = +new Date();
|
||||
if (now - ts > 5000) {
|
||||
equal("no result", 0);
|
||||
start();
|
||||
clearInterval(id);
|
||||
}
|
||||
}
|
||||
|
||||
}, 50);
|
||||
});
|
||||
|
||||
// SOME TESTS ON THE LOCAL WEBSERVER -- ignore unless allowLocalWebServer set at top
|
||||
if (allowLocalWebServer) {
|
||||
|
||||
var serverPath = "http://localhost/ritajs/test/html/data/";
|
||||
|
||||
asyncTest("RiTa.loadString1(url)", function() {
|
||||
|
||||
RiTa.loadString(serverPath+"sentence1.json", function(s) {
|
||||
|
||||
ok(s && s.length > 100);
|
||||
//console.log("JSON:",s);
|
||||
ok(JSON.parse(s));
|
||||
start();
|
||||
});
|
||||
});
|
||||
|
||||
asyncTest("RiTa.loadString2(url)", function() {
|
||||
|
||||
RiTa.loadString(serverPath+"kafka.txt", function(s) {
|
||||
ok(s && s.length > 65536);
|
||||
start();
|
||||
});
|
||||
});
|
||||
|
||||
asyncTest("RiGrammar.loadFrom(Url)", function() {
|
||||
|
||||
var grammar = new RiGrammar();
|
||||
grammar.loadFrom(serverPath+"/haikuGrammar.json");
|
||||
|
||||
var ts = +new Date();
|
||||
var id = setInterval(function() {
|
||||
if (grammar.ready()) {
|
||||
ok(grammar);
|
||||
start();
|
||||
clearInterval(id);
|
||||
} else {
|
||||
var now = +new Date();
|
||||
if (now - ts > 5000) {
|
||||
equal("no result", 0);
|
||||
start();
|
||||
clearInterval(id);
|
||||
}
|
||||
}
|
||||
|
||||
}, 50);
|
||||
});
|
||||
|
||||
asyncTest("RiMarkov.loadFromUrl", function() { // SLOW
|
||||
|
||||
var rm = new RiMarkov(3);
|
||||
rm.loadFrom(serverPath+"kafka.txt");
|
||||
|
||||
var ts = +new Date();
|
||||
var id = setInterval(function() {
|
||||
|
||||
if (rm.ready()) {
|
||||
//console.log("RiMarkov.loadFromUrl: "+rm.size());
|
||||
ok(rm.size());
|
||||
var s = rm.generateSentence();
|
||||
//console.log("RiMarkov.loadFromUrl: "+s);
|
||||
ok(s);
|
||||
|
||||
// TODO: 2 more better tests here
|
||||
clearInterval(id);
|
||||
start();
|
||||
|
||||
} else {
|
||||
|
||||
var now = +new Date();
|
||||
if (now - ts > 5000) {
|
||||
equal("no result", 0);
|
||||
start();
|
||||
clearInterval(id);
|
||||
}
|
||||
}
|
||||
}, 50);
|
||||
});
|
||||
}
|
||||
else {
|
||||
console.log("[INFO] UrlLoading: skipping webserver tests");
|
||||
}
|
||||
|
||||
}// end runtests
|
||||
|
||||
if (typeof exports != 'undefined') {
|
||||
try {
|
||||
YAML = require('yamljs');
|
||||
}
|
||||
catch(e) {
|
||||
console.log("[WARN] require() didn't find a YAML parser");
|
||||
}
|
||||
runtests();
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
{
|
||||
"<start>": "<5-line> % <7-line> % <5-line>",
|
||||
"<5-line>": "<1> <4> |<1> <3> <1> |<1> <1> <3> | <1> <2> <2> | <1> <2> <1> <1> | <1> <1> <2> <1> | <1> <1> <1> <2> | <1> <1> <1> <1> <1> | <2> <3> | <2> <2> <1> | <2> <1> <2> | <2> <1> <1> <1> | <3> <2> | <3> <1> <1> | <4> <1> | <5>",
|
||||
"<7-line>": "<1> <1> <5-line> | <2> <5-line> | <5-line> <1> <1> | <5-line> <2>",
|
||||
"<1>": "red | white | black | sky | dawns | breaks | falls | leaf | rain | pool | my | your | sun | clouds | blue | green | night | day | dawn | dusk | birds | fly | grass | tree | branch | through | hell | zen | smile | gray | wave | sea | through | sound | mind | smoke | cranes | fish",
|
||||
"<2>": "drifting | purple | mountains | skyline | city | faces | toward | empty | buddhist | temple | japan | under | ocean | thinking | zooming | rushing | over | rice field | rising | falling | sparkling | snowflake",
|
||||
"<3>": "sunrises | pheasant farms | people farms | samurai | juniper | fishing boats | far away | kimonos | evenings | peasant rain | sad snow fall",
|
||||
"<4>": "aluminum | yakitori | the east village | west of the sun | chrysanthemums | cherry blossoms",
|
||||
"<5>": "resolutional | non-elemental | rolling foothills rise | toward mountains higher | out over this country | in the springtime again"
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
---
|
||||
<start>: <5-line> % <7-line> % <5-line>
|
||||
<5-line>: <1> <4> |<1> <3> <1> |<1> <1> <3> | <1> <2> <2> | <1> <2> <1> <1> | <1> <1> <2> <1> | <1> <1> <1> <2> | <1> <1> <1> <1> <1> | <2> <3> | <2> <2> <1> | <2> <1> <2> | <2> <1> <1> <1> | <3> <2> | <3> <1> <1> | <4> <1> | <5>
|
||||
<7-line>: <1> <1> <5-line> | <2> <5-line> | <5-line> <1> <1> | <5-line> <2>
|
||||
<1>: red | white | black | sky | dawns | breaks | falls | leaf | rain | pool | my | your | sun | clouds | blue | green | night | day | dawn | dusk | birds | fly | grass | tree | branch | through | hell | zen | smile | gray | wave | sea | through | sound | mind | smoke | cranes | fish
|
||||
<2>: drifting | purple | mountains | skyline | city | faces | toward | empty | buddhist | temple | japan | under | ocean | thinking | zooming | rushing | over | rice field | rising | falling | sparkling | snowflake
|
||||
<3>: sunrises | pheasant farms | people farms | samurai | juniper | fishing boats | far away | kimonos | evenings | peasant rain | sad snow fall
|
||||
<4>: aluminum | yakitori | the east village | west of the sun | chrysanthemums | cherry blossoms
|
||||
<5>: resolutional | non-elemental | rolling foothills rise | toward mountains higher | out over this country | in the springtime again
|
@ -0,0 +1,122 @@
|
||||
{
|
||||
"<start>": [
|
||||
"<5-line> % <7-line> % <5-line>"
|
||||
],
|
||||
"<5-line>": [
|
||||
"<1> <4>",
|
||||
"<1> <3> <1>",
|
||||
"<1> <1> <3>",
|
||||
"<1> <2> <2>",
|
||||
"<1> <2> <1> <1>",
|
||||
"<1> <1> <2> <1>",
|
||||
"<1> <1> <1> <2>",
|
||||
"<1> <1> <1> <1> <1>",
|
||||
"<2> <3>",
|
||||
"<2> <2> <1>",
|
||||
"<2> <1> <2>",
|
||||
"<2> <1> <1> <1>",
|
||||
"<3> <2>",
|
||||
"<3> <1> <1>",
|
||||
"<4> <1>",
|
||||
"<5>"
|
||||
],
|
||||
"<7-line>": [
|
||||
"<1> <1> <5-line>",
|
||||
"<2> <5-line>",
|
||||
"<5-line> <1> <1>",
|
||||
"<5-line> <2>"
|
||||
],
|
||||
"<1>": [
|
||||
"red",
|
||||
"white",
|
||||
"black",
|
||||
"sky",
|
||||
"dawns",
|
||||
"breaks",
|
||||
"falls",
|
||||
"leaf",
|
||||
"rain",
|
||||
"pool",
|
||||
"my",
|
||||
"your",
|
||||
"sun",
|
||||
"clouds",
|
||||
"blue",
|
||||
"green",
|
||||
"night",
|
||||
"day",
|
||||
"dawn",
|
||||
"dusk",
|
||||
"birds",
|
||||
"fly",
|
||||
"grass",
|
||||
"tree",
|
||||
"branch",
|
||||
"through",
|
||||
"hell",
|
||||
"zen",
|
||||
"smile",
|
||||
"gray",
|
||||
"wave",
|
||||
"sea",
|
||||
"through",
|
||||
"sound",
|
||||
"mind",
|
||||
"smoke",
|
||||
"cranes",
|
||||
"fish"
|
||||
],
|
||||
"<2>": [
|
||||
"drifting",
|
||||
"purple",
|
||||
"mountains",
|
||||
"skyline",
|
||||
"city",
|
||||
"faces",
|
||||
"toward",
|
||||
"empty",
|
||||
"buddhist",
|
||||
"temple",
|
||||
"japan",
|
||||
"under",
|
||||
"ocean",
|
||||
"thinking",
|
||||
"zooming",
|
||||
"rushing",
|
||||
"over",
|
||||
"rice field",
|
||||
"rising",
|
||||
"falling",
|
||||
"sparkling",
|
||||
"snowflake"
|
||||
],
|
||||
"<3>": [
|
||||
"sunrises",
|
||||
"pheasant farms",
|
||||
"people farms",
|
||||
"samurai",
|
||||
"juniper",
|
||||
"fishing boats",
|
||||
"far away",
|
||||
"kimonos",
|
||||
"evenings",
|
||||
"peasant rain",
|
||||
"sad snow fall"
|
||||
],
|
||||
"<4>": [
|
||||
"aluminum",
|
||||
"yakitori",
|
||||
"the east village",
|
||||
"west of the sun",
|
||||
"chrysanthemums",
|
||||
"cherry blossoms"
|
||||
],
|
||||
"<5>": [
|
||||
"resolutional",
|
||||
"non-elemental",
|
||||
"rolling foothills rise",
|
||||
"toward mountains higher",
|
||||
"out over this country",
|
||||
"in the springtime again"
|
||||
]
|
||||
}
|
@ -0,0 +1,120 @@
|
||||
---
|
||||
<start>:
|
||||
- <5-line> % <7-line> % <5-line>
|
||||
|
||||
<5-line>:
|
||||
- <1> <4>
|
||||
- <1> <3> <1>
|
||||
- <1> <1> <3>
|
||||
- <1> <2> <2>
|
||||
- <1> <2> <1> <1>
|
||||
- <1> <1> <2> <1>
|
||||
- <1> <1> <1> <2>
|
||||
- <1> <1> <1> <1> <1>
|
||||
- <2> <3>
|
||||
- <2> <2> <1>
|
||||
- <2> <1> <2>
|
||||
- <2> <1> <1> <1>
|
||||
- <3> <2>
|
||||
- <3> <1> <1>
|
||||
- <4> <1>
|
||||
- <5>
|
||||
|
||||
<7-line>:
|
||||
- <1> <1> <5-line>
|
||||
- <2> <5-line>
|
||||
- <5-line> <1> <1>
|
||||
- <5-line> <2>
|
||||
|
||||
<1>:
|
||||
- red
|
||||
- white
|
||||
- black
|
||||
- sky
|
||||
- dawns
|
||||
- breaks
|
||||
- falls
|
||||
- leaf
|
||||
- rain
|
||||
- pool
|
||||
- my
|
||||
- your
|
||||
- sun
|
||||
- clouds
|
||||
- blue
|
||||
- green
|
||||
- night
|
||||
- day
|
||||
- dawn
|
||||
- dusk
|
||||
- birds
|
||||
- fly
|
||||
- grass
|
||||
- tree
|
||||
- branch
|
||||
- through
|
||||
- hell
|
||||
- zen
|
||||
- smile
|
||||
- gray
|
||||
- wave
|
||||
- sea
|
||||
- through
|
||||
- sound
|
||||
- mind
|
||||
- smoke
|
||||
- cranes
|
||||
- fish
|
||||
|
||||
<2>:
|
||||
- drifting
|
||||
- purple
|
||||
- mountains
|
||||
- skyline
|
||||
- city
|
||||
- faces
|
||||
- toward
|
||||
- empty
|
||||
- buddhist
|
||||
- temple
|
||||
- japan
|
||||
- under
|
||||
- ocean
|
||||
- thinking
|
||||
- zooming
|
||||
- rushing
|
||||
- over
|
||||
- rice field
|
||||
- rising
|
||||
- falling
|
||||
- sparkling
|
||||
- snowflake
|
||||
|
||||
<3>:
|
||||
- sunrises
|
||||
- pheasant farms
|
||||
- people farms
|
||||
- samurai
|
||||
- juniper
|
||||
- fishing boats
|
||||
- far away
|
||||
- kimonos
|
||||
- evenings
|
||||
- peasant rain
|
||||
- sad snow fall
|
||||
|
||||
<4>:
|
||||
- aluminum
|
||||
- yakitori
|
||||
- the east village
|
||||
- west of the sun
|
||||
- chrysanthemums
|
||||
- cherry blossoms
|
||||
|
||||
<5>:
|
||||
- resolutional
|
||||
- non-elemental
|
||||
- rolling foothills rise
|
||||
- toward mountains higher
|
||||
- out over this country
|
||||
- in the springtime again
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,8 @@
|
||||
{
|
||||
"<start>" : "<noun_phrase> <verb_phrase>.",
|
||||
"<noun_phrase>" : "<determiner> <noun>",
|
||||
"<determiner>" : "a [0.1] | the",
|
||||
"<verb_phrase>" : "<verb> | <verb> <noun_phrase> [0.1]",
|
||||
"<noun>" : "woman | man",
|
||||
"<verb>" : "shoots"
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
---
|
||||
<determiner>: a [0.1] | the
|
||||
#I am a comment
|
||||
<noun>: woman | man
|
||||
<noun_phrase>: <determiner> <noun>
|
||||
<start>: <noun_phrase> <verb_phrase>.
|
||||
<verb>: shoots
|
||||
<verb_phrase>: <verb> | <verb> <noun_phrase> [0.1]
|
@ -0,0 +1,17 @@
|
||||
{
|
||||
"<start>": "<noun_phrase> <verb_phrase>.",
|
||||
"<noun_phrase>": "<determiner> <noun>",
|
||||
"<determiner>": [
|
||||
"a [0.1]",
|
||||
"the"
|
||||
],
|
||||
"<verb_phrase>": [
|
||||
"<verb> <noun_phrase> [0.1]",
|
||||
"<verb>"
|
||||
],
|
||||
"<noun>": [
|
||||
"woman",
|
||||
"man"
|
||||
],
|
||||
"<verb>": "shoots"
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
---
|
||||
<determiner>:
|
||||
- "a [0.1]"
|
||||
- the
|
||||
<noun>:
|
||||
- woman
|
||||
- man
|
||||
# I am a comment
|
||||
<noun_phrase>: "<determiner> <noun>"
|
||||
<start>: "<noun_phrase> <verb_phrase>."
|
||||
<verb>: shoots
|
||||
<verb_phrase>:
|
||||
- <verb> <noun_phrase> [0.1]
|
||||
- <verb>
|
@ -0,0 +1 @@
|
||||
A huge lizard was discovered drinking out of the fountain today. It was not menacing anyone, it was just very thirsty. A small crowd gathered and whispered to one another, as though the lizard would understand them if they spoke in normal voices. The lizard seemed not even a little perturbed by their gathering. It drank and drank, its long forked tongue was like a red river hypnotizing the people, keeping them in a trance-like state. 'It's like a different town,' one of them whispered. 'Change is good,' the other one whispered back.
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,90 @@
|
||||
/*jslint node: true*/
|
||||
/*global equal, expect, require, ok, QUnit */
|
||||
|
||||
/*
|
||||
* loads the JSON doc-file and checks that each described field actually exists in the object
|
||||
*/
|
||||
QUnit.checkAPI = function(className, Class, obj, pathToDocs) {
|
||||
|
||||
var eles = QUnit.propertiesFromAPI(pathToDocs, className);
|
||||
|
||||
if (!eles) {
|
||||
|
||||
expect(0);
|
||||
console.warn("[WARN] Skipped checkAPI() test for '" + className + "'");
|
||||
return;
|
||||
}
|
||||
|
||||
for (var i = 0; eles && i < eles.length; i++) {
|
||||
|
||||
//console.log("Checking "+eles[i].name);
|
||||
|
||||
if (!eles[i] || eles[i] === 'undefined') {
|
||||
|
||||
console.log("Null element in " + className.json);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (eles[i].isVar) {
|
||||
|
||||
ok(obj.hasOwnProperty(eles[i].name), 'property: ' + eles[i].name);
|
||||
|
||||
} else if (eles[i].isStatic) {
|
||||
|
||||
equal(typeof Class[eles[i].name], 'function', 'static-function: ' + eles[i].name + '()');
|
||||
|
||||
} else {
|
||||
|
||||
equal(typeof obj[eles[i].name], 'function', 'function: ' + eles[i].name + '()');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/*
|
||||
* loads the JSON doc-file and populates and array of 'field' objects, where a field
|
||||
* contains a 'name' string, and 2 booleans: 'isVar' and 'isStatic'.
|
||||
*/
|
||||
QUnit.propertiesFromAPI = function(pathToDocs, className) {
|
||||
|
||||
var jsonf, fields, elements = [];
|
||||
|
||||
// for now, this only works in Node (and not from the browser OR an NPM package)
|
||||
if (typeof exports != 'undefined') {
|
||||
|
||||
jsonf = pathToDocs + className;
|
||||
try {
|
||||
fields = require(jsonf).fields;
|
||||
} catch (e) {
|
||||
|
||||
console.warn("[WARN] No json file at '" + jsonf + ".json', or perhaps the JSON is invalid?");
|
||||
return;
|
||||
}
|
||||
|
||||
for (var i = 0, j = fields.length; i < j; i++) {
|
||||
|
||||
if (fields[i].hidden) continue;
|
||||
|
||||
var isVar = fields[i].variable || false,
|
||||
isStatic = (new RegExp("^" + className + ".").test(fields[i].name)),
|
||||
name = isStatic ? fields[i].name.substring(className.length + 1) : fields[i].name;
|
||||
|
||||
elements.push({
|
||||
name: name,
|
||||
isVar: isVar,
|
||||
isStatic: isStatic
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return elements;
|
||||
};
|
||||
|
||||
// Adds some logging to the command-line (Node) test script
|
||||
QUnit.moduleStart(function(n) {
|
||||
console.log("[INFO] Testing " + n.name);
|
||||
});
|
||||
|
||||
// Adds some logging to the command-line (Node) test script
|
||||
QUnit.moduleDone(function(n) {
|
||||
//console.log("[INFO] Completed "+n.name);
|
||||
});
|
@ -0,0 +1,6 @@
|
||||
var RiTa = require('rita');
|
||||
|
||||
var rs = RiTa.RiString("The elephant took a bite!");
|
||||
var features = rs.features();
|
||||
|
||||
console.log(features);
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue