This commit is contained in:
hatuhn
2019-09-13 09:44:33 +07:00
parent 1f1633e801
commit f14a34ba19
16798 changed files with 1652961 additions and 4327 deletions

175
node_modules/coa/lib/arg.js generated vendored Normal file
View File

@@ -0,0 +1,175 @@
// Generated by CoffeeScript 1.6.3
var Arg, Cmd, Color, Opt;
Color = require('./color').Color;
Cmd = require('./cmd').Cmd;
Opt = require('./opt').Opt;
/**
Argument
Unnamed entity. From command line arguments passed as list of unnamed values.
@namespace
@class Presents argument
*/
exports.Arg = Arg = (function() {
/**
@constructs
@param {COA.Cmd} cmd parent command
*/
function Arg(_cmd) {
this._cmd = _cmd;
this._cmd._args.push(this);
}
/**
Set a canonical argument identifier to be used anywhere in text messages.
@param {String} _name argument name
@returns {COA.Arg} this instance (for chainability)
*/
Arg.prototype.name = Opt.prototype.name;
/**
Set a long description for argument to be used anywhere in text messages.
@param {String} _title argument title
@returns {COA.Arg} this instance (for chainability)
*/
Arg.prototype.title = Cmd.prototype.title;
/**
Makes an argument accepts multiple values.
Otherwise, the value will be used by the latter passed.
@returns {COA.Arg} this instance (for chainability)
*/
Arg.prototype.arr = Opt.prototype.arr;
/**
Makes an argument required.
@returns {COA.Arg} this instance (for chainability)
*/
Arg.prototype.req = Opt.prototype.req;
/**
Set a validation (or value) function for argument.
Value from command line passes through before becoming available from API.
Using for validation and convertion simple types to any values.
@param {Function} _val validating function,
invoked in the context of argument instance
and has one parameter with value from command line
@returns {COA.Arg} this instance (for chainability)
*/
Arg.prototype.val = Opt.prototype.val;
/**
Set a default value for argument.
Default value passed through validation function as ordinary value.
@param {Object} _def
@returns {COA.Arg} this instance (for chainability)
*/
Arg.prototype.def = Opt.prototype.def;
/**
Set custom additional completion for current argument.
@param {Function} completion generation function,
invoked in the context of argument instance.
Accepts parameters:
- {Object} opts completion options
It can return promise or any other value treated as result.
@returns {COA.Arg} this instance (for chainability)
*/
Arg.prototype.comp = Cmd.prototype.comp;
/**
Make argument value inputting stream.
It's add useful validation and shortcut for STDIN.
@returns {COA.Arg} this instance (for chainability)
*/
Arg.prototype.input = Opt.prototype.input;
/**
Make argument value outputing stream.
It's add useful validation and shortcut for STDOUT.
@returns {COA.Arg} this instance (for chainability)
*/
Arg.prototype.output = Opt.prototype.output;
Arg.prototype._parse = function(arg, args) {
return this._saveVal(args, arg);
};
Arg.prototype._saveVal = Opt.prototype._saveVal;
Arg.prototype._checkParsed = function(opts, args) {
return !args.hasOwnProperty(this._name);
};
Arg.prototype._usage = function() {
var res;
res = [];
res.push(Color('lpurple', this._name.toUpperCase()), ' : ', this._title);
if (this._req) {
res.push(' ', Color('lred', '(required)'));
}
return res.join('');
};
Arg.prototype._requiredText = function() {
return 'Missing required argument:\n ' + this._usage();
};
/**
Return rejected promise with error code.
Use in .val() for return with error.
@param {Object} reject reason
You can customize toString() method and exitCode property
of reason object.
@returns {Q.promise} rejected promise
*/
Arg.prototype.reject = Cmd.prototype.reject;
/**
Finish chain for current option and return parent command instance.
@returns {COA.Cmd} parent command
*/
Arg.prototype.end = Cmd.prototype.end;
/**
Apply function with arguments in context of arg instance.
@param {Function} fn
@param {Array} args
@returns {COA.Arg} this instance (for chainability)
*/
Arg.prototype.apply = Cmd.prototype.apply;
return Arg;
})();

605
node_modules/coa/lib/cmd.js generated vendored Normal file
View File

@@ -0,0 +1,605 @@
// Generated by CoffeeScript 1.6.3
var Cmd, Color, PATH, Q, UTIL,
__slice = [].slice;
UTIL = require('util');
PATH = require('path');
Color = require('./color').Color;
Q = require('q');
/**
Command
Top level entity. Commands may have options and arguments.
@namespace
@class Presents command
*/
exports.Cmd = Cmd = (function() {
/**
@constructs
@param {COA.Cmd} [cmd] parent command
*/
function Cmd(cmd) {
if (!(this instanceof Cmd)) {
return new Cmd(cmd);
}
this._parent(cmd);
this._cmds = [];
this._cmdsByName = {};
this._opts = [];
this._optsByKey = {};
this._args = [];
this._ext = false;
}
Cmd.get = function(propertyName, func) {
return Object.defineProperty(this.prototype, propertyName, {
configurable: true,
enumerable: true,
get: func
});
};
/**
Returns object containing all its subcommands as methods
to use from other programs.
@returns {Object}
*/
Cmd.get('api', function() {
var c, _fn,
_this = this;
if (!this._api) {
this._api = function() {
return _this.invoke.apply(_this, arguments);
};
}
_fn = function(c) {
return _this._api[c] = _this._cmdsByName[c].api;
};
for (c in this._cmdsByName) {
_fn(c);
}
return this._api;
});
Cmd.prototype._parent = function(cmd) {
this._cmd = cmd || this;
if (cmd) {
cmd._cmds.push(this);
if (this._name) {
this._cmd._cmdsByName[this._name] = this;
}
}
return this;
};
/**
Set a canonical command identifier to be used anywhere in the API.
@param {String} _name command name
@returns {COA.Cmd} this instance (for chainability)
*/
Cmd.prototype.name = function(_name) {
this._name = _name;
if (this._cmd !== this) {
this._cmd._cmdsByName[_name] = this;
}
return this;
};
/**
Set a long description for command to be used anywhere in text messages.
@param {String} _title command title
@returns {COA.Cmd} this instance (for chainability)
*/
Cmd.prototype.title = function(_title) {
this._title = _title;
return this;
};
/**
Create new or add existing subcommand for current command.
@param {COA.Cmd} [cmd] existing command instance
@returns {COA.Cmd} new subcommand instance
*/
Cmd.prototype.cmd = function(cmd) {
if (cmd) {
return cmd._parent(this);
} else {
return new Cmd(this);
}
};
/**
Create option for current command.
@returns {COA.Opt} new option instance
*/
Cmd.prototype.opt = function() {
return new (require('./opt').Opt)(this);
};
/**
Create argument for current command.
@returns {COA.Opt} new argument instance
*/
Cmd.prototype.arg = function() {
return new (require('./arg').Arg)(this);
};
/**
Add (or set) action for current command.
@param {Function} act action function,
invoked in the context of command instance
and has the parameters:
- {Object} opts parsed options
- {Array} args parsed arguments
- {Object} res actions result accumulator
It can return rejected promise by Cmd.reject (in case of error)
or any other value treated as result.
@param {Boolean} [force=false] flag for set action instead add to existings
@returns {COA.Cmd} this instance (for chainability)
*/
Cmd.prototype.act = function(act, force) {
if (!act) {
return this;
}
if (!force && this._act) {
this._act.push(act);
} else {
this._act = [act];
}
return this;
};
/**
Set custom additional completion for current command.
@param {Function} completion generation function,
invoked in the context of command instance.
Accepts parameters:
- {Object} opts completion options
It can return promise or any other value treated as result.
@returns {COA.Cmd} this instance (for chainability)
*/
Cmd.prototype.comp = function(_comp) {
this._comp = _comp;
return this;
};
/**
Apply function with arguments in context of command instance.
@param {Function} fn
@param {Array} args
@returns {COA.Cmd} this instance (for chainability)
*/
Cmd.prototype.apply = function() {
var args, fn;
fn = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
fn.apply(this, args);
return this;
};
/**
Make command "helpful", i.e. add -h --help flags for print usage.
@returns {COA.Cmd} this instance (for chainability)
*/
Cmd.prototype.helpful = function() {
return this.opt().name('help').title('Help').short('h').long('help').flag().only().act(function() {
return this.usage();
}).end();
};
/**
Adds shell completion to command, adds "completion" subcommand,
that makes all the magic.
Must be called only on root command.
@returns {COA.Cmd} this instance (for chainability)
*/
Cmd.prototype.completable = function() {
return this.cmd().name('completion').apply(require('./completion')).end();
};
/**
Allow command to be extendable by external node.js modules.
@param {String} [pattern] Pattern of node.js module to find subcommands at.
@returns {COA.Cmd} this instance (for chainability)
*/
Cmd.prototype.extendable = function(pattern) {
this._ext = pattern || true;
return this;
};
Cmd.prototype._exit = function(msg, code) {
return process.once('exit', function() {
if (msg) {
console.error(msg);
}
return process.exit(code || 0);
});
};
/**
Build full usage text for current command instance.
@returns {String} usage text
*/
Cmd.prototype.usage = function() {
var res;
res = [];
if (this._title) {
res.push(this._fullTitle());
}
res.push('', 'Usage:');
if (this._cmds.length) {
res.push(['', '', Color('lred', this._fullName()), Color('lblue', 'COMMAND'), Color('lgreen', '[OPTIONS]'), Color('lpurple', '[ARGS]')].join(' '));
}
if (this._opts.length + this._args.length) {
res.push(['', '', Color('lred', this._fullName()), Color('lgreen', '[OPTIONS]'), Color('lpurple', '[ARGS]')].join(' '));
}
res.push(this._usages(this._cmds, 'Commands'), this._usages(this._opts, 'Options'), this._usages(this._args, 'Arguments'));
return res.join('\n');
};
Cmd.prototype._usage = function() {
return Color('lblue', this._name) + ' : ' + this._title;
};
Cmd.prototype._usages = function(os, title) {
var o, res, _i, _len;
if (!os.length) {
return;
}
res = ['', title + ':'];
for (_i = 0, _len = os.length; _i < _len; _i++) {
o = os[_i];
res.push(' ' + o._usage());
}
return res.join('\n');
};
Cmd.prototype._fullTitle = function() {
return (this._cmd === this ? '' : this._cmd._fullTitle() + '\n') + this._title;
};
Cmd.prototype._fullName = function() {
return (this._cmd === this ? '' : this._cmd._fullName() + ' ') + PATH.basename(this._name);
};
Cmd.prototype._ejectOpt = function(opts, opt) {
var pos;
if ((pos = opts.indexOf(opt)) >= 0) {
if (opts[pos]._arr) {
return opts[pos];
} else {
return opts.splice(pos, 1)[0];
}
}
};
Cmd.prototype._checkRequired = function(opts, args) {
var all, i;
if (!(this._opts.filter(function(o) {
return o._only && o._name in opts;
})).length) {
all = this._opts.concat(this._args);
while (i = all.shift()) {
if (i._req && i._checkParsed(opts, args)) {
return this.reject(i._requiredText());
}
}
}
};
Cmd.prototype._parseCmd = function(argv, unparsed) {
var c, cmd, cmdDesc, e, i, optSeen, pkg;
if (unparsed == null) {
unparsed = [];
}
argv = argv.concat();
optSeen = false;
while (i = argv.shift()) {
if (!i.indexOf('-')) {
optSeen = true;
}
if (!optSeen && /^\w[\w-_]*$/.test(i)) {
cmd = this._cmdsByName[i];
if (!cmd && this._ext) {
if (typeof this._ext === 'string') {
if (~this._ext.indexOf('%s')) {
pkg = UTIL.format(this._ext, i);
} else {
pkg = this._ext + i;
}
} else if (this._ext === true) {
pkg = i;
c = this;
while (true) {
pkg = c._name + '-' + pkg;
if (c._cmd === c) {
break;
}
c = c._cmd;
}
}
try {
cmdDesc = require(pkg);
} catch (_error) {
e = _error;
}
if (cmdDesc) {
if (typeof cmdDesc === 'function') {
this.cmd().name(i).apply(cmdDesc).end();
} else if (typeof cmdDesc === 'object') {
this.cmd(cmdDesc);
cmdDesc.name(i);
} else {
throw new Error('Error: Unsupported command declaration type, ' + 'should be function or COA.Cmd() object');
}
cmd = this._cmdsByName[i];
}
}
if (cmd) {
return cmd._parseCmd(argv, unparsed);
}
}
unparsed.push(i);
}
return {
cmd: this,
argv: unparsed
};
};
Cmd.prototype._parseOptsAndArgs = function(argv) {
var a, arg, args, i, m, nonParsedArgs, nonParsedOpts, opt, opts, res;
opts = {};
args = {};
nonParsedOpts = this._opts.concat();
nonParsedArgs = this._args.concat();
while (i = argv.shift()) {
if (i !== '--' && !i.indexOf('-')) {
if (m = i.match(/^(--\w[\w-_]*)=(.*)$/)) {
i = m[1];
if (!this._optsByKey[i]._flag) {
argv.unshift(m[2]);
}
}
if (opt = this._ejectOpt(nonParsedOpts, this._optsByKey[i])) {
if (Q.isRejected(res = opt._parse(argv, opts))) {
return res;
}
} else {
return this.reject("Unknown option: " + i);
}
} else {
if (i === '--') {
i = argv.splice(0);
}
i = Array.isArray(i) ? i : [i];
while (a = i.shift()) {
if (arg = nonParsedArgs.shift()) {
if (arg._arr) {
nonParsedArgs.unshift(arg);
}
if (Q.isRejected(res = arg._parse(a, args))) {
return res;
}
} else {
return this.reject("Unknown argument: " + a);
}
}
}
}
return {
opts: this._setDefaults(opts, nonParsedOpts),
args: this._setDefaults(args, nonParsedArgs)
};
};
Cmd.prototype._setDefaults = function(params, desc) {
var i, _i, _len;
for (_i = 0, _len = desc.length; _i < _len; _i++) {
i = desc[_i];
if (!(i._name in params) && '_def' in i) {
i._saveVal(params, i._def);
}
}
return params;
};
Cmd.prototype._processParams = function(params, desc) {
var i, n, notExists, res, v, vals, _i, _j, _len, _len1;
notExists = [];
for (_i = 0, _len = desc.length; _i < _len; _i++) {
i = desc[_i];
n = i._name;
if (!(n in params)) {
notExists.push(i);
continue;
}
vals = params[n];
delete params[n];
if (!Array.isArray(vals)) {
vals = [vals];
}
for (_j = 0, _len1 = vals.length; _j < _len1; _j++) {
v = vals[_j];
if (Q.isRejected(res = i._saveVal(params, v))) {
return res;
}
}
}
return this._setDefaults(params, notExists);
};
Cmd.prototype._parseArr = function(argv) {
return Q.when(this._parseCmd(argv), function(p) {
return Q.when(p.cmd._parseOptsAndArgs(p.argv), function(r) {
return {
cmd: p.cmd,
opts: r.opts,
args: r.args
};
});
});
};
Cmd.prototype._do = function(input) {
var _this = this;
return Q.when(input, function(input) {
var cmd;
cmd = input.cmd;
return [_this._checkRequired].concat(cmd._act || []).reduce(function(res, act) {
return Q.when(res, function(res) {
return act.call(cmd, input.opts, input.args, res);
});
}, void 0);
});
};
/**
Parse arguments from simple format like NodeJS process.argv
and run ahead current program, i.e. call process.exit when all actions done.
@param {Array} argv
@returns {COA.Cmd} this instance (for chainability)
*/
Cmd.prototype.run = function(argv) {
var cb,
_this = this;
if (argv == null) {
argv = process.argv.slice(2);
}
cb = function(code) {
return function(res) {
var _ref, _ref1;
if (res) {
return _this._exit((_ref = res.stack) != null ? _ref : res.toString(), (_ref1 = res.exitCode) != null ? _ref1 : code);
} else {
return _this._exit();
}
};
};
Q.when(this["do"](argv), cb(0), cb(1)).done();
return this;
};
/**
Convenient function to run command from tests.
@param {Array} argv
@returns {Q.Promise}
*/
Cmd.prototype["do"] = function(argv) {
return this._do(this._parseArr(argv || []));
};
/**
Invoke specified (or current) command using provided
options and arguments.
@param {String|Array} cmds subcommand to invoke (optional)
@param {Object} opts command options (optional)
@param {Object} args command arguments (optional)
@returns {Q.Promise}
*/
Cmd.prototype.invoke = function(cmds, opts, args) {
var _this = this;
if (cmds == null) {
cmds = [];
}
if (opts == null) {
opts = {};
}
if (args == null) {
args = {};
}
if (typeof cmds === 'string') {
cmds = cmds.split(' ');
}
if (arguments.length < 3) {
if (!Array.isArray(cmds)) {
args = opts;
opts = cmds;
cmds = [];
}
}
return Q.when(this._parseCmd(cmds), function(p) {
if (p.argv.length) {
return _this.reject("Unknown command: " + cmds.join(' '));
}
return Q.all([_this._processParams(opts, _this._opts), _this._processParams(args, _this._args)]).spread(function(opts, args) {
return _this._do({
cmd: p.cmd,
opts: opts,
args: args
}).fail(function(res) {
if (res && res.exitCode === 0) {
return res.toString();
} else {
return _this.reject(res);
}
});
});
});
};
/**
Return reject of actions results promise with error code.
Use in .act() for return with error.
@param {Object} reject reason
You can customize toString() method and exitCode property
of reason object.
@returns {Q.promise} rejected promise
*/
Cmd.prototype.reject = function(reason) {
return Q.reject(reason);
};
/**
Finish chain for current subcommand and return parent command instance.
@returns {COA.Cmd} parent command
*/
Cmd.prototype.end = function() {
return this._cmd;
};
return Cmd;
})();

25
node_modules/coa/lib/color.js generated vendored Normal file
View File

@@ -0,0 +1,25 @@
// Generated by CoffeeScript 1.6.3
var colors;
colors = {
black: '30',
dgray: '1;30',
red: '31',
lred: '1;31',
green: '32',
lgreen: '1;32',
brown: '33',
yellow: '1;33',
blue: '34',
lblue: '1;34',
purple: '35',
lpurple: '1;35',
cyan: '36',
lcyan: '1;36',
lgray: '37',
white: '1;37'
};
exports.Color = function(c, str) {
return ['\x1B[', colors[c], 'm', str, '\x1B[m'].join('');
};

134
node_modules/coa/lib/completion.js generated vendored Normal file
View File

@@ -0,0 +1,134 @@
// Generated by CoffeeScript 1.6.3
/**
Most of the code adopted from the npm package shell completion code.
See https://github.com/isaacs/npm/blob/master/lib/completion.js
*/
var Q, complete, dumpScript, escape, getOpts, unescape;
Q = require('q');
escape = require('./shell').escape;
unescape = require('./shell').unescape;
module.exports = function() {
return this.title('Shell completion').helpful().arg().name('raw').title('Completion words').arr().end().act(function(opts, args) {
var argv, cmd, e, _ref;
if (process.platform === 'win32') {
e = new Error('shell completion not supported on windows');
e.code = 'ENOTSUP';
e.errno = require('constants').ENOTSUP;
return this.reject(e);
}
if ((process.env.COMP_CWORD == null) || (process.env.COMP_LINE == null) || (process.env.COMP_POINT == null)) {
return dumpScript(this._cmd._name);
}
console.error('COMP_LINE: %s', process.env.COMP_LINE);
console.error('COMP_CWORD: %s', process.env.COMP_CWORD);
console.error('COMP_POINT: %s', process.env.COMP_POINT);
console.error('args: %j', args.raw);
opts = getOpts(args.raw);
_ref = this._cmd._parseCmd(opts.partialWords), cmd = _ref.cmd, argv = _ref.argv;
return Q.when(complete(cmd, opts), function(compls) {
console.error('filtered: %j', compls);
return console.log(compls.map(escape).join('\n'));
});
});
};
dumpScript = function(name) {
var defer, fs, path;
fs = require('fs');
path = require('path');
defer = Q.defer();
fs.readFile(path.resolve(__dirname, 'completion.sh'), 'utf8', function(err, d) {
var onError;
if (err) {
return defer.reject(err);
}
d = d.replace(/{{cmd}}/g, path.basename(name)).replace(/^\#\!.*?\n/, '');
onError = function(err) {
if (err.errno === require('constants').EPIPE) {
process.stdout.removeListener('error', onError);
return defer.resolve();
} else {
return defer.reject(err);
}
};
process.stdout.on('error', onError);
return process.stdout.write(d, function() {
return defer.resolve();
});
});
return defer.promise;
};
getOpts = function(argv) {
var i, line, partialLine, partialWord, partialWords, point, w, word, words;
line = process.env.COMP_LINE;
w = +process.env.COMP_CWORD;
point = +process.env.COMP_POINT;
words = argv.map(unescape);
word = words[w];
partialLine = line.substr(0, point);
partialWords = words.slice(0, w);
partialWord = argv[w] || '';
i = partialWord.length;
while (partialWord.substr(0, i) !== partialLine.substr(-1 * i) && i > 0) {
i--;
}
partialWord = unescape(partialWord.substr(0, i));
if (partialWord) {
partialWords.push(partialWord);
}
return {
line: line,
w: w,
point: point,
words: words,
word: word,
partialLine: partialLine,
partialWords: partialWords,
partialWord: partialWord
};
};
complete = function(cmd, opts) {
var compls, m, o, opt, optPrefix, optWord;
compls = [];
if (opts.partialWord.indexOf('-')) {
compls = Object.keys(cmd._cmdsByName);
} else {
if (m = opts.partialWord.match(/^(--\w[\w-_]*)=(.*)$/)) {
optWord = m[1];
optPrefix = optWord + '=';
} else {
compls = Object.keys(cmd._optsByKey);
}
}
if (!(o = opts.partialWords[opts.w - 1]).indexOf('-')) {
optWord = o;
}
if (optWord && (opt = cmd._optsByKey[optWord])) {
if (!opt._flag && opt._comp) {
compls = Q.join(compls, Q.when(opt._comp(opts), function(c, o) {
return c.concat(o.map(function(v) {
return (optPrefix || '') + v;
}));
}));
}
}
if (cmd._comp) {
compls = Q.join(compls, Q.when(cmd._comp(opts)), function(c, o) {
return c.concat(o);
});
}
return Q.when(compls, function(compls) {
console.error('partialWord: %s', opts.partialWord);
console.error('compls: %j', compls);
return compls.filter(function(c) {
return c.indexOf(opts.partialWord) === 0;
});
});
};

43
node_modules/coa/lib/completion.sh generated vendored Normal file
View File

@@ -0,0 +1,43 @@
#!/usr/bin/env bash
###-begin-{{cmd}}-completion-###
#
# {{cmd}} command completion script
#
# Installation: {{cmd}} completion >> ~/.bashrc (or ~/.zshrc)
# Or, maybe: {{cmd}} completion > /usr/local/etc/bash_completion.d/{{cmd}}
#
COMP_WORDBREAKS=${COMP_WORDBREAKS/=/}
COMP_WORDBREAKS=${COMP_WORDBREAKS/@/}
export COMP_WORDBREAKS
if complete &>/dev/null; then
_{{cmd}}_completion () {
local si="$IFS"
IFS=$'\n' COMPREPLY=($(COMP_CWORD="$COMP_CWORD" \
COMP_LINE="$COMP_LINE" \
COMP_POINT="$COMP_POINT" \
{{cmd}} completion -- "${COMP_WORDS[@]}" \
2>/dev/null)) || return $?
IFS="$si"
}
complete -F _{{cmd}}_completion {{cmd}}
elif compctl &>/dev/null; then
_{{cmd}}_completion () {
local cword line point words si
read -Ac words
read -cn cword
let cword-=1
read -l line
read -ln point
si="$IFS"
IFS=$'\n' reply=($(COMP_CWORD="$cword" \
COMP_LINE="$line" \
COMP_POINT="$point" \
{{cmd}} completion -- "${words[@]}" \
2>/dev/null)) || return $?
IFS="$si"
}
compctl -K _{{cmd}}_completion {{cmd}}
fi
###-end-{{cmd}}-completion-###

10
node_modules/coa/lib/index.js generated vendored Normal file
View File

@@ -0,0 +1,10 @@
// Generated by CoffeeScript 1.6.3
exports.Cmd = require('./cmd').Cmd;
exports.Opt = require('./cmd').Opt;
exports.Arg = require('./cmd').Arg;
exports.shell = require('./shell');
exports.require = require;

338
node_modules/coa/lib/opt.js generated vendored Normal file
View File

@@ -0,0 +1,338 @@
// Generated by CoffeeScript 1.6.3
var Cmd, Color, Opt, Q, fs;
fs = require('fs');
Q = require('q');
Color = require('./color').Color;
Cmd = require('./cmd').Cmd;
/**
Option
Named entity. Options may have short and long keys for use from command line.
@namespace
@class Presents option
*/
exports.Opt = Opt = (function() {
/**
@constructs
@param {COA.Cmd} cmd parent command
*/
function Opt(_cmd) {
this._cmd = _cmd;
this._cmd._opts.push(this);
}
/**
Set a canonical option identifier to be used anywhere in the API.
@param {String} _name option name
@returns {COA.Opt} this instance (for chainability)
*/
Opt.prototype.name = function(_name) {
this._name = _name;
return this;
};
/**
Set a long description for option to be used anywhere in text messages.
@param {String} _title option title
@returns {COA.Opt} this instance (for chainability)
*/
Opt.prototype.title = Cmd.prototype.title;
/**
Set a short key for option to be used with one hyphen from command line.
@param {String} _short
@returns {COA.Opt} this instance (for chainability)
*/
Opt.prototype.short = function(_short) {
this._short = _short;
return this._cmd._optsByKey['-' + _short] = this;
};
/**
Set a short key for option to be used with double hyphens from command line.
@param {String} _long
@returns {COA.Opt} this instance (for chainability)
*/
Opt.prototype.long = function(_long) {
this._long = _long;
return this._cmd._optsByKey['--' + _long] = this;
};
/**
Make an option boolean, i.e. option without value.
@returns {COA.Opt} this instance (for chainability)
*/
Opt.prototype.flag = function() {
this._flag = true;
return this;
};
/**
Makes an option accepts multiple values.
Otherwise, the value will be used by the latter passed.
@returns {COA.Opt} this instance (for chainability)
*/
Opt.prototype.arr = function() {
this._arr = true;
return this;
};
/**
Makes an option required.
@returns {COA.Opt} this instance (for chainability)
*/
Opt.prototype.req = function() {
this._req = true;
return this;
};
/**
Makes an option to act as a command,
i.e. program will exit just after option action.
@returns {COA.Opt} this instance (for chainability)
*/
Opt.prototype.only = function() {
this._only = true;
return this;
};
/**
Set a validation (or value) function for option.
Value from command line passes through before becoming available from API.
Using for validation and convertion simple types to any values.
@param {Function} _val validating function,
invoked in the context of option instance
and has one parameter with value from command line
@returns {COA.Opt} this instance (for chainability)
*/
Opt.prototype.val = function(_val) {
this._val = _val;
return this;
};
/**
Set a default value for option.
Default value passed through validation function as ordinary value.
@param {Object} _def
@returns {COA.Opt} this instance (for chainability)
*/
Opt.prototype.def = function(_def) {
this._def = _def;
return this;
};
/**
Make option value inputting stream.
It's add useful validation and shortcut for STDIN.
@returns {COA.Opt} this instance (for chainability)
*/
Opt.prototype.input = function() {
process.stdin.pause();
return this.def(process.stdin).val(function(v) {
var s;
if (typeof v === 'string') {
if (v === '-') {
return process.stdin;
} else {
s = fs.createReadStream(v, {
encoding: 'utf8'
});
s.pause();
return s;
}
} else {
return v;
}
});
};
/**
Make option value outputing stream.
It's add useful validation and shortcut for STDOUT.
@returns {COA.Opt} this instance (for chainability)
*/
Opt.prototype.output = function() {
return this.def(process.stdout).val(function(v) {
if (typeof v === 'string') {
if (v === '-') {
return process.stdout;
} else {
return fs.createWriteStream(v, {
encoding: 'utf8'
});
}
} else {
return v;
}
});
};
/**
Add action for current option command.
This action is performed if the current option
is present in parsed options (with any value).
@param {Function} act action function,
invoked in the context of command instance
and has the parameters:
- {Object} opts parsed options
- {Array} args parsed arguments
- {Object} res actions result accumulator
It can return rejected promise by Cmd.reject (in case of error)
or any other value treated as result.
@returns {COA.Opt} this instance (for chainability)
*/
Opt.prototype.act = function(act) {
var name, opt;
opt = this;
name = this._name;
this._cmd.act(function(opts) {
var res,
_this = this;
if (name in opts) {
res = act.apply(this, arguments);
if (opt._only) {
return Q.when(res, function(res) {
return _this.reject({
toString: function() {
return res.toString();
},
exitCode: 0
});
});
} else {
return res;
}
}
});
return this;
};
/**
Set custom additional completion for current option.
@param {Function} completion generation function,
invoked in the context of option instance.
Accepts parameters:
- {Object} opts completion options
It can return promise or any other value treated as result.
@returns {COA.Opt} this instance (for chainability)
*/
Opt.prototype.comp = Cmd.prototype.comp;
Opt.prototype._saveVal = function(opts, val) {
var _name;
if (this._val) {
val = this._val(val);
}
if (this._arr) {
(opts[_name = this._name] || (opts[_name] = [])).push(val);
} else {
opts[this._name] = val;
}
return val;
};
Opt.prototype._parse = function(argv, opts) {
return this._saveVal(opts, this._flag ? true : argv.shift());
};
Opt.prototype._checkParsed = function(opts, args) {
return !opts.hasOwnProperty(this._name);
};
Opt.prototype._usage = function() {
var nameStr, res;
res = [];
nameStr = this._name.toUpperCase();
if (this._short) {
res.push('-', Color('lgreen', this._short));
if (!this._flag) {
res.push(' ' + nameStr);
}
res.push(', ');
}
if (this._long) {
res.push('--', Color('green', this._long));
if (!this._flag) {
res.push('=' + nameStr);
}
}
res.push(' : ', this._title);
if (this._req) {
res.push(' ', Color('lred', '(required)'));
}
return res.join('');
};
Opt.prototype._requiredText = function() {
return 'Missing required option:\n ' + this._usage();
};
/**
Return rejected promise with error code.
Use in .val() for return with error.
@param {Object} reject reason
You can customize toString() method and exitCode property
of reason object.
@returns {Q.promise} rejected promise
*/
Opt.prototype.reject = Cmd.prototype.reject;
/**
Finish chain for current option and return parent command instance.
@returns {COA.Cmd} parent command
*/
Opt.prototype.end = Cmd.prototype.end;
/**
Apply function with arguments in context of option instance.
@param {Function} fn
@param {Array} args
@returns {COA.Opt} this instance (for chainability)
*/
Opt.prototype.apply = Cmd.prototype.apply;
return Opt;
})();

14
node_modules/coa/lib/shell.js generated vendored Normal file
View File

@@ -0,0 +1,14 @@
// Generated by CoffeeScript 1.6.3
exports.unescape = function(w) {
w = w.charAt(0) === '"' ? w.replace(/^"|([^\\])"$/g, '$1') : w.replace(/\\ /g, ' ');
return w.replace(/\\("|'|\$|`|\\)/g, '$1');
};
exports.escape = function(w) {
w = w.replace(/(["'$`\\])/g, '\\$1');
if (w.match(/\s+/)) {
return '"' + w + '"';
} else {
return w;
}
};