readline-sync/lib/readline-sync.js

1228 lines
40 KiB
JavaScript
Raw Normal View History

2013-08-29 12:55:23 +02:00
/*
* readlineSync
* https://github.com/anseki/readline-sync
*
2015-01-26 17:11:25 +01:00
* Copyright (c) 2015 anseki
2013-08-29 12:55:23 +02:00
* Licensed under the MIT license.
*/
'use strict';
2014-07-13 06:55:17 +02:00
var
IS_WIN = process.platform === 'win32',
2014-07-13 06:55:17 +02:00
ALGORITHM_CIPHER = 'aes-256-cbc',
ALGORITHM_HASH = 'sha256',
2015-03-06 07:23:32 +01:00
DEFAULT_ERR_MSG = 'The platform doesn\'t support interactive reading',
2014-07-13 06:55:17 +02:00
2013-08-29 19:26:22 +02:00
fs = require('fs'),
2015-03-20 04:03:58 +01:00
TTY = process.binding('tty_wrap').TTY,
childProc = require('child_process'),
2015-04-04 17:37:42 +02:00
defaultOptions = {
2015-04-07 11:38:14 +02:00
prompt: '> ',
hideEchoBack: false,
mask: '*',
limit: [],
limitMessage: 'Input another, please.${( [)limit(])}',
2015-04-14 18:05:24 +02:00
defaultInput: '',
2015-04-13 08:55:33 +02:00
trueValue: [],
falseValue: [],
2015-04-07 11:38:14 +02:00
caseSensitive: false,
keepWhitespace: false,
encoding: 'utf8',
bufferSize: 1024,
print: void 0,
2015-04-14 18:05:24 +02:00
history: true,
cd: false,
2015-04-17 11:08:22 +02:00
phContent: void 0,
preCheck: void 0
2015-04-04 17:37:42 +02:00
},
2015-03-20 04:03:58 +01:00
fdR = 'none', fdW, ttyR, isRawMode = false,
extHostPath, extHostArgs, tempdir, salt = 0,
2015-04-13 08:55:33 +02:00
lastInput = '', inputHistory = [],
_DBG_useExt = false, _DBG_checkOptions = false, _DBG_checkMethod = false;
2013-08-29 12:55:23 +02:00
/*
2015-04-07 11:38:14 +02:00
display: string
2015-04-13 08:55:33 +02:00
displayOnly: boolean
2015-04-07 11:38:14 +02:00
keyIn: boolean
hideEchoBack: boolean
mask: string
limit: string (pattern)
caseSensitive: boolean
keepWhitespace: boolean
encoding, bufferSize, print
*/
2015-04-05 13:05:23 +02:00
function _readlineSync(options) {
var input = '', displaySave = options.display,
2015-04-07 11:38:14 +02:00
silent = !options.display &&
options.keyIn && options.hideEchoBack && !options.mask;
2013-12-18 03:51:32 +01:00
function tryExt() {
var res = readlineExt(options);
2015-03-07 16:19:40 +01:00
if (res.error) { throw res.error; }
2015-03-20 04:03:58 +01:00
return res.input;
}
if (_DBG_checkOptions) { _DBG_checkOptions(options); }
2015-03-31 13:27:02 +02:00
(function() { // open TTY
2015-03-20 04:03:58 +01:00
var fsB, constants;
function getFsB() {
if (!fsB) {
fsB = process.binding('fs'); // For raw device path
constants = process.binding('constants');
}
return fsB;
}
2015-03-07 16:19:40 +01:00
2015-03-20 04:03:58 +01:00
if (typeof fdR !== 'string') { return; }
fdR = null;
if (IS_WIN) {
if (process.stdin.isTTY) {
fdR = process.stdin.fd;
ttyR = process.stdin._handle;
} else {
2015-03-07 16:19:40 +01:00
try {
2015-03-20 04:03:58 +01:00
// The stream by fs.openSync('\\\\.\\CON', 'r') can't switch to raw mode.
// 'CONIN$' might fail on XP, 2000, 7 (x86).
fdR = getFsB().open('CONIN$', constants.O_RDWR, parseInt('0666', 8));
ttyR = new TTY(fdR, true);
2015-03-07 16:19:40 +01:00
} catch (e) {}
2015-03-20 04:03:58 +01:00
}
2015-03-07 16:19:40 +01:00
2015-03-20 04:03:58 +01:00
if (process.stdout.isTTY) {
fdW = process.stdout.fd;
} else {
try {
fdW = fs.openSync('\\\\.\\CON', 'w');
} catch (e) {}
if (typeof fdW !== 'number') { // Retry
2015-03-07 16:19:40 +01:00
try {
2015-03-20 04:03:58 +01:00
fdW = getFsB().open('CONOUT$', constants.O_RDWR, parseInt('0666', 8));
2015-03-07 16:19:40 +01:00
} catch (e) {}
}
}
2014-07-12 00:37:25 +02:00
2015-03-11 09:06:27 +01:00
} else {
2015-03-20 04:03:58 +01:00
if (process.stdin.isTTY) {
try {
fdR = fs.openSync('/dev/tty', 'r'); // device file, not process.stdin
ttyR = process.stdin._handle;
} catch (e) {}
} else {
// Node v0.12 read() fails.
try {
fdR = fs.openSync('/dev/tty', 'r');
ttyR = new TTY(fdR, false);
} catch (e) {}
}
if (process.stdout.isTTY) {
fdW = process.stdout.fd;
} else {
try {
fdW = fs.openSync('/dev/tty', 'w');
} catch (e) {}
}
2015-03-07 16:19:40 +01:00
}
2015-03-20 04:03:58 +01:00
})();
(function() { // try read
var atEol, limit,
2015-04-07 11:38:14 +02:00
isCooked = !options.hideEchoBack && !options.keyIn,
2015-04-01 09:34:31 +02:00
buffer, reqSize, readSize, chunk, line;
2015-03-25 13:22:44 +01:00
// Node v0.10- returns an error if same mode is set.
function setRawMode(mode) {
if (mode === isRawMode) { return true; }
if (ttyR.setRawMode(mode) !== 0) { return false; }
isRawMode = mode;
return true;
}
2015-03-07 16:19:40 +01:00
if (_DBG_useExt || !ttyR ||
2015-04-04 17:37:42 +02:00
typeof fdW !== 'number' && (options.display || !isCooked)) {
input = tryExt();
2015-03-20 04:03:58 +01:00
return;
}
2015-03-31 13:27:02 +02:00
if (options.display) {
fs.writeSync(fdW, options.display);
2015-03-20 04:03:58 +01:00
options.display = '';
}
2015-04-13 08:55:33 +02:00
if (options.displayOnly) { return; }
2015-03-20 04:03:58 +01:00
2015-03-29 16:45:55 +02:00
if (!setRawMode(!isCooked)) {
input = tryExt();
2015-03-20 04:03:58 +01:00
return;
}
buffer = new Buffer((reqSize = options.keyIn ? 1 : options.bufferSize));
2015-03-20 04:03:58 +01:00
if (options.keyIn && options.limit) {
2015-04-04 17:37:42 +02:00
limit = new RegExp('[^' + options.limit + ']',
'g' + (options.caseSensitive ? '' : 'i'));
2015-03-31 13:27:02 +02:00
}
2015-03-20 04:03:58 +01:00
while (true) {
readSize = 0;
try {
readSize = fs.readSync(fdR, buffer, 0, reqSize);
} catch (e) {
2015-03-29 16:45:55 +02:00
if (e.code !== 'EOF') {
setRawMode(false);
input += tryExt();
return;
}
}
2015-04-04 17:37:42 +02:00
chunk = readSize > 0 ? buffer.toString(options.encoding, 0, readSize) : '\n';
2015-03-29 16:45:55 +02:00
2015-04-13 08:55:33 +02:00
if (chunk && typeof(line = (chunk.match(/^(.*?)[\r\n]/) || [])[1]) === 'string') {
2015-03-29 16:45:55 +02:00
chunk = line;
2015-04-01 09:34:31 +02:00
atEol = true;
2013-12-17 18:18:39 +01:00
}
2014-07-12 00:37:25 +02:00
// other ctrl-chars
if (chunk) { chunk = chunk.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, ''); }
if (chunk && limit) { chunk = chunk.replace(limit, ''); }
2015-03-20 04:03:58 +01:00
if (chunk) {
if (!isCooked) {
2015-04-07 11:38:14 +02:00
if (!options.hideEchoBack) {
fs.writeSync(fdW, chunk);
} else if (options.mask) {
fs.writeSync(fdW, (new Array(chunk.length + 1)).join(options.mask));
}
2015-03-22 06:11:55 +01:00
}
input += chunk;
2015-03-20 04:03:58 +01:00
}
2015-04-01 09:34:31 +02:00
if (!options.keyIn && atEol ||
options.keyIn && input.length >= reqSize) { break; }
2013-12-17 18:18:39 +01:00
}
2013-12-18 03:51:32 +01:00
2015-03-31 13:27:02 +02:00
if (!isCooked && !silent) { fs.writeSync(fdW, '\n'); }
2015-03-20 04:03:58 +01:00
setRawMode(false);
})();
2015-04-13 08:55:33 +02:00
if (options.print && !silent) {
options.print(displaySave + (options.displayOnly ? '' :
(options.hideEchoBack ? (new Array(input.length + 1)).join(options.mask)
: input) + '\n'), // must at least write '\n'
2015-04-04 17:37:42 +02:00
options.encoding);
2013-08-29 12:55:23 +02:00
}
2015-04-13 08:55:33 +02:00
return options.displayOnly ? '' :
(lastInput = options.keepWhitespace || options.keyIn ? input : input.trim());
}
function readlineExt(options) {
var hostArgs, res = {},
2015-04-04 17:37:42 +02:00
execOptions = {env: process.env, encoding: options.encoding};
if (!extHostPath) {
if (IS_WIN) {
if (process.env.PSModulePath) { // Windows PowerShell
extHostPath = 'powershell.exe';
extHostArgs = ['-ExecutionPolicy', 'Bypass', '-File', __dirname + '\\read.ps1'];
} else { // Windows Script Host
extHostPath = 'cscript.exe';
extHostArgs = ['//nologo', __dirname + '\\read.cs.js'];
}
} else {
extHostPath = '/bin/sh';
extHostArgs = [__dirname + '/read.sh'];
}
2015-03-11 09:06:27 +01:00
}
if (IS_WIN && !process.env.PSModulePath) { // Windows Script Host
// ScriptPW (Win XP and Server2003) needs TTY stream as STDIN.
// In this case, If STDIN isn't TTY, an error is thrown.
execOptions.stdio = [process.stdin];
}
if (childProc.execFileSync) {
hostArgs = getHostArgs(options);
if (_DBG_checkMethod) { _DBG_checkMethod('execFileSync', hostArgs); }
2015-03-03 18:30:41 +01:00
try {
res.input = childProc.execFileSync(extHostPath, hostArgs, execOptions);
2015-03-03 18:30:41 +01:00
} catch (e) { // non-zero exit code
2015-03-06 07:23:32 +01:00
res.error = new Error(DEFAULT_ERR_MSG);
res.error.method = 'execFileSync';
res.error.program = extHostPath;
res.error.args = hostArgs;
res.error.extMessage = e.stderr.trim();
res.error.exitCode = e.status;
2015-03-17 04:11:46 +01:00
res.error.code = e.code;
res.error.signal = e.signal;
2015-03-03 18:30:41 +01:00
}
} else {
res = _execFileSync(options, execOptions);
}
2015-03-13 10:34:41 +01:00
if (!res.error) {
2015-03-30 12:36:31 +02:00
res.input = res.input.replace(/^\s*'|'\s*$/g, '');
2015-03-13 10:34:41 +01:00
options.display = '';
}
2015-03-03 18:30:41 +01:00
return res;
}
// piping via files (for Node v0.10-)
function _execFileSync(options, execOptions) {
function getTempfile(name) {
2015-04-16 12:08:04 +02:00
var pathUtil = require('path'), filepath, suffix = '', fd;
tempdir = tempdir || require('os').tmpdir();
while (true) {
2015-04-16 12:08:04 +02:00
filepath = pathUtil.join(tempdir, name + suffix);
try {
fd = fs.openSync(filepath, 'wx');
} catch (e) {
if (e.code === 'EEXIST') {
suffix++;
continue;
} else {
throw e;
}
}
fs.closeSync(fd);
break;
}
return filepath;
}
var hostArgs, shellPath, shellArgs, res = {}, exitCode,
2015-03-13 10:34:41 +01:00
pathStdout = getTempfile('readline-sync.stdout'),
pathStderr = getTempfile('readline-sync.stderr'),
pathExit = getTempfile('readline-sync.exit'),
pathDone = getTempfile('readline-sync.done'),
2014-07-13 06:55:17 +02:00
crypto = require('crypto'), shasum, decipher, password;
shasum = crypto.createHash(ALGORITHM_HASH);
shasum.update('' + process.pid + (salt++) + Math.random());
password = shasum.digest('hex');
decipher = crypto.createDecipher(ALGORITHM_CIPHER, password);
hostArgs = getHostArgs(options);
2015-03-02 14:44:36 +01:00
if (IS_WIN) {
shellPath = process.env.ComSpec || 'cmd.exe';
2015-03-07 16:19:40 +01:00
process.env.Q = '"'; // The quote (") that isn't escaped.
2015-03-03 18:30:41 +01:00
// `()` for ignore space by echo
shellArgs = ['/V:ON', '/S', '/C',
'(%Q%' + shellPath + '%Q% /V:ON /S /C %Q%' +
'%Q%' + extHostPath + '%Q%' +
hostArgs.map(function(arg) { return ' %Q%' + arg + '%Q%'; }).join('') +
2015-03-13 10:34:41 +01:00
' & (echo !ERRORLEVEL!)>%Q%' + pathExit + '%Q%%Q%) 2>%Q%' + pathStderr + '%Q%' +
2015-03-02 14:44:36 +01:00
' |%Q%' + process.execPath + '%Q% %Q%' + __dirname + '\\encrypt.js%Q%' +
' %Q%' + ALGORITHM_CIPHER + '%Q% %Q%' + password + '%Q%' +
2015-03-03 18:30:41 +01:00
' >%Q%' + pathStdout + '%Q%' +
' & (echo 1)>%Q%' + pathDone + '%Q%'];
2015-03-02 14:44:36 +01:00
} else {
shellPath = '/bin/sh';
shellArgs = ['-c',
2015-03-05 09:39:46 +01:00
// Use `()`, not `{}` for `-c` (text param)
'("' + extHostPath + '"' +
hostArgs.map(function(arg)
2015-03-13 10:34:41 +01:00
{ return " '" + arg.replace(/'/g, "'\\''") + "'"; }).join('') +
'; echo $?>"' + pathExit + '") 2>"' + pathStderr + '"' +
2015-03-02 14:44:36 +01:00
' |"' + process.execPath + '" "' + __dirname + '/encrypt.js"' +
' "' + ALGORITHM_CIPHER + '" "' + password + '"' +
2015-03-03 18:30:41 +01:00
' >"' + pathStdout + '"' +
'; echo 1 >"' + pathDone + '"'];
2015-03-02 14:44:36 +01:00
}
if (_DBG_checkMethod) { _DBG_checkMethod('_execFileSync', hostArgs); }
2015-03-13 10:34:41 +01:00
try {
childProc.spawn(shellPath, shellArgs, execOptions);
2015-03-13 10:34:41 +01:00
} catch (e) {
res.error = new Error(e.message);
res.error.method = '_execFileSync - spawn';
res.error.program = shellPath;
res.error.args = shellArgs;
2015-03-13 10:34:41 +01:00
}
2015-04-04 17:37:42 +02:00
while (fs.readFileSync(pathDone, {encoding: options.encoding}).trim() !== '1') {}
if ((exitCode =
fs.readFileSync(pathExit, {encoding: options.encoding}).trim()) === '0') {
2015-03-06 07:23:32 +01:00
res.input =
2015-04-04 17:37:42 +02:00
decipher.update(fs.readFileSync(pathStdout, {encoding: 'binary'}),
'hex', options.encoding) +
decipher.final(options.encoding);
2015-03-03 18:30:41 +01:00
} else {
2015-03-06 07:23:32 +01:00
res.error = new Error(DEFAULT_ERR_MSG);
res.error.method = '_execFileSync';
res.error.program = shellPath;
res.error.args = shellArgs;
2015-04-04 17:37:42 +02:00
res.error.extMessage =
fs.readFileSync(pathStderr, {encoding: options.encoding}).trim();
2015-03-17 04:11:46 +01:00
res.error.exitCode = +exitCode;
}
fs.unlinkSync(pathStdout);
2015-03-03 18:30:41 +01:00
fs.unlinkSync(pathStderr);
2015-03-13 10:34:41 +01:00
fs.unlinkSync(pathExit);
fs.unlinkSync(pathDone);
2015-03-03 18:30:41 +01:00
return res;
}
function getHostArgs(options) {
// Send any text to crazy Windows shell safely.
function encodeArg(arg) {
return arg.replace(/[^\w\u0080-\uFFFF]/g, function(chr) {
return '#' + chr.charCodeAt(0) + ';';
});
}
return extHostArgs.concat((function(conf) {
2015-04-05 07:45:42 +02:00
var args = [];
Object.keys(conf).forEach(function(optionName) {
if (conf[optionName] === 'boolean') {
if (options[optionName]) { args.push('--' + optionName); }
} else if (conf[optionName] === 'string') {
if (options[optionName]) {
args.push('--' + optionName, encodeArg(options[optionName]));
}
}
2015-04-05 07:45:42 +02:00
});
return args;
})({
2015-03-31 13:27:02 +02:00
display: 'string',
2015-04-13 08:55:33 +02:00
displayOnly: 'boolean',
2015-03-31 13:27:02 +02:00
keyIn: 'boolean',
2015-04-07 11:38:14 +02:00
hideEchoBack: 'boolean',
2015-03-31 13:27:02 +02:00
mask: 'string',
limit: 'string',
caseSensitive: 'boolean'
}));
}
2015-04-07 11:38:14 +02:00
function flattenArray(array, validator) {
var flatArray = [];
function _flattenArray(array) {
2015-04-13 08:55:33 +02:00
/* jshint eqnull:true */
2015-04-07 11:38:14 +02:00
if (array == null) { return; }
2015-04-13 08:55:33 +02:00
/* jshint eqnull:false */
else if (Array.isArray(array)) { array.forEach(_flattenArray); }
2015-04-07 11:38:14 +02:00
else if (!validator || validator(array)) { flatArray.push(array); }
}
_flattenArray(array);
2015-04-07 11:38:14 +02:00
return flatArray;
}
2015-04-05 07:45:42 +02:00
// margeOptions(options1, options2 ... )
// margeOptions(true, options1, options2 ... )
// arg1=true : Start from defaultOptions and pick elements of that.
2015-04-04 17:37:42 +02:00
function margeOptions() {
2015-04-05 07:45:42 +02:00
var optionsList = Array.prototype.slice.call(arguments),
optionNames, fromDefault;
if (optionsList.length && typeof optionsList[0] === 'boolean') {
fromDefault = optionsList.shift();
if (fromDefault) {
optionNames = Object.keys(defaultOptions);
optionsList.unshift(defaultOptions);
}
}
return optionsList.reduce(function(options, optionsPart) {
2015-04-13 08:55:33 +02:00
/* jshint eqnull:true */
2015-04-05 07:45:42 +02:00
if (optionsPart == null) { return options; }
2015-04-13 08:55:33 +02:00
/* jshint eqnull:false */
2015-04-05 07:45:42 +02:00
// ======== DEPRECATED ========
if (optionsPart.hasOwnProperty('noEchoBack') &&
!optionsPart.hasOwnProperty('hideEchoBack')) {
optionsPart.hideEchoBack = optionsPart.noEchoBack;
delete optionsPart.noEchoBack;
}
if (optionsPart.hasOwnProperty('noTrim') &&
!optionsPart.hasOwnProperty('keepWhitespace')) {
optionsPart.keepWhitespace = optionsPart.noTrim;
delete optionsPart.noTrim;
}
// ======== /DEPRECATED ========
2015-04-05 07:45:42 +02:00
if (!fromDefault) { optionNames = Object.keys(optionsPart); }
optionNames.forEach(function(optionName) {
var value;
if (!optionsPart.hasOwnProperty(optionName)) { return; }
value = optionsPart[optionName];
switch (optionName) {
2015-04-14 18:05:24 +02:00
// _readlineSync <- * * -> defaultOptions
2015-04-07 11:38:14 +02:00
// ================ string
2015-04-05 07:45:42 +02:00
case 'mask': // * *
2015-04-05 13:05:23 +02:00
case 'limitMessage': // *
2015-04-14 18:05:24 +02:00
case 'defaultInput': // *
2015-04-13 08:55:33 +02:00
case 'encoding': // * *
/* jshint eqnull:true */
2015-04-07 11:38:14 +02:00
value = value != null ? value + '' : '';
2015-04-13 08:55:33 +02:00
/* jshint eqnull:false */
2015-04-14 18:05:24 +02:00
if (value && optionName !== 'limitMessage')
2015-04-07 11:38:14 +02:00
{ value = value.replace(/[\r\n]/g, ''); }
options[optionName] = value;
2015-04-05 07:45:42 +02:00
break;
2015-04-13 08:55:33 +02:00
// ================ number(int)
case 'bufferSize': // * *
2015-04-05 07:45:42 +02:00
if (!isNaN(value = parseInt(value, 10)) && typeof value === 'number')
{ options[optionName] = value; } // limited updating (number is needed)
2015-04-05 07:45:42 +02:00
break;
2015-04-07 11:38:14 +02:00
// ================ boolean
2015-04-13 08:55:33 +02:00
case 'displayOnly': // *
case 'keyIn': // *
2015-04-07 11:38:14 +02:00
case 'hideEchoBack': // * *
2015-04-05 07:45:42 +02:00
case 'caseSensitive': // * *
2015-04-07 11:38:14 +02:00
case 'keepWhitespace': // * *
2015-04-13 08:55:33 +02:00
case 'history': // *
2015-04-14 18:05:24 +02:00
case 'cd': // *
2015-04-05 07:45:42 +02:00
options[optionName] = !!value;
break;
2015-04-07 11:38:14 +02:00
// ================ array
2015-04-13 08:55:33 +02:00
case 'limit': // * * to string for readlineExt
2015-04-07 11:38:14 +02:00
case 'trueValue': // *
case 'falseValue': // *
options[optionName] = flattenArray(value, function(value) {
var type = typeof value;
return type === 'string' || type === 'number' ||
type === 'function' || value instanceof RegExp;
}).map(function(value) {
return typeof value === 'string' ? value.replace(/[\r\n]/g, '') : value;
});
break;
2015-04-13 08:55:33 +02:00
// ================ function
case 'print': // * *
2015-04-14 18:05:24 +02:00
case 'phContent': // *
2015-04-17 11:08:22 +02:00
case 'preCheck': // *
2015-04-13 08:55:33 +02:00
options[optionName] = typeof value === 'function' ? value : void 0;
break;
2015-04-07 11:38:14 +02:00
// ================ other
2015-04-05 07:45:42 +02:00
case 'prompt': // *
2015-04-13 08:55:33 +02:00
case 'display': // *
/* jshint eqnull:true */
2015-04-05 07:45:42 +02:00
options[optionName] = value != null ? value : '';
2015-04-13 08:55:33 +02:00
/* jshint eqnull:false */
2015-04-05 07:45:42 +02:00
break;
}
});
return options;
}, {});
2015-04-04 17:37:42 +02:00
}
function isMatched(res, comps, caseSensitive) {
return comps.some(function(comp) {
var type = typeof comp;
2015-04-13 08:55:33 +02:00
return type === 'string' ?
(caseSensitive ? res === comp : res.toLowerCase() === comp.toLowerCase()) :
2015-04-13 08:55:33 +02:00
type === 'number' ? parseFloat(res) === comp :
type === 'function' ? comp(res) :
2015-04-13 08:55:33 +02:00
comp instanceof RegExp ? comp.test(res) : false;
2015-04-05 13:05:23 +02:00
});
}
2015-04-07 11:38:14 +02:00
function replacePlaceholder(text, generator) {
return text.replace(/(\$)?(\$\{(?:\(([\s\S]*?)\))?(\w+|.-.)(?:\(([\s\S]*?)\))?\})/g,
function(str, escape, placeholder, pre, param, post) {
var text;
return escape || typeof(text = generator(param)) !== 'string' ? placeholder :
text ? (pre || '') + text + (post || '') : '';
});
}
function array2charlist(array, caseSensitive, collectSymbols) {
var values, group = [], groupClass = -1, charCode = 0, symbols = '', suppressed;
function addGroup(groups, group) {
if (group.length > 3) { // ellipsis
groups.push(group[0] + '...' + group[group.length - 1]);
suppressed = true;
} else if (group.length) {
groups = groups.concat(group);
}
return groups;
}
values = array.reduce(function(chars, value)
{ return chars.concat((value + '').split('')); }, [])
.reduce(function(groups, curChar) {
var curGroupClass, curCharCode;
2015-04-14 18:05:24 +02:00
if (!caseSensitive) { curChar = curChar.toLowerCase(); }
curGroupClass = /^\d$/.test(curChar) ? 1 :
/^[A-Z]$/.test(curChar) ? 2 : /^[a-z]$/.test(curChar) ? 3 : 0;
if (collectSymbols && curGroupClass === 0) {
symbols += curChar;
} else {
curCharCode = curChar.charCodeAt(0);
if (curGroupClass && curGroupClass === groupClass &&
curCharCode === charCode + 1) {
group.push(curChar);
} else {
groups = addGroup(groups, group);
group = [curChar];
groupClass = curGroupClass;
}
charCode = curCharCode;
}
return groups;
}, []);
values = addGroup(values, group); // last group
if (symbols) { values.push(symbols); suppressed = true; }
return {values: values, suppressed: suppressed};
}
function joinChunks(chunks, suppressed)
{ return chunks.join(chunks.length > 2 ? ', ' : suppressed ? ' / ' : '/'); }
2015-04-13 08:55:33 +02:00
function getPhContent(param, options) {
2015-04-14 18:05:24 +02:00
var text, values, resCharlist = {}, path, arg;
if (options.phContent) {
text = options.phContent(param, options);
}
if (typeof text !== 'string') {
switch (param) {
case 'hideEchoBack':
case 'mask':
case 'defaultInput':
case 'caseSensitive':
case 'keepWhitespace':
case 'encoding':
case 'bufferSize':
case 'history':
case 'cd':
text = !options.hasOwnProperty(param) ? '' :
typeof options[param] === 'boolean' ? (options[param] ? 'on' : 'off') :
options[param] + '';
break;
// case 'prompt':
// case 'query':
// case 'display':
// text = options.hasOwnProperty('displaySrc') ? options.displaySrc + '' : '';
// break;
case 'limit':
case 'trueValue':
case 'falseValue':
values = options[options.hasOwnProperty(param + 'Src') ? param + 'Src' : param];
if (options.keyIn) { // suppress
resCharlist = array2charlist(values, options.caseSensitive);
values = resCharlist.values;
} else {
values = values.filter(function(value) {
var type = typeof value;
return type === 'string' || type === 'number';
});
}
text = joinChunks(values, resCharlist.suppressed);
break;
case 'limitCount':
case 'limitCountNotZero':
text = options[options.hasOwnProperty('limitSrc') ?
'limitSrc' : 'limit'].length;
text = text || param !== 'limitCountNotZero' ? text + '' : '';
break;
case 'lastInput':
text = lastInput;
break;
case 'cwd':
case 'CWD':
case 'cwdHome':
text = process.cwd();
if (param === 'CWD') { text = require('path').basename(text); }
else if (param === 'cwdHome') {
path = (IS_WIN ? ((process.env.HOMEDRIVE || '') +
(process.env.HOMEPATH || '')).toLowerCase() :
process.env.HOME || '').replace(/[\/\\]+$/, '');
if (path && (IS_WIN ? text.toLowerCase() : text).indexOf(path) === 0)
{ text = '~' + text.substr(path.length); }
}
break;
case 'date':
case 'time':
case 'localeDate':
case 'localeTime':
text = (new Date())['to' +
param.replace(/^./, function(str) { return str.toUpperCase(); }) +
'String']();
break;
default: // with arg
if (typeof(arg = (param.match(/^history_m(\d+)$/) || [])[1]) === 'string') {
text = inputHistory[inputHistory.length - arg] || '';
}
}
2015-04-07 11:38:14 +02:00
}
return text;
}
2015-04-13 08:55:33 +02:00
function getPhCharlist(param) {
var matches = /^(.)-(.)$/.exec(param), text = '', from, to, code, step;
if (!matches) { return; }
from = matches[1].charCodeAt(0);
to = matches[2].charCodeAt(0);
step = from < to ? 1 : -1;
for (code = from; code !== to + step; code += step)
{ text += String.fromCharCode(code); }
return text;
}
2015-04-17 11:08:22 +02:00
// cmd "arg" " a r g " "" 'a"r"g' "a""rg" "arg
function parseCl(cl) {
2015-04-16 12:08:04 +02:00
var reToken = new RegExp(/(\s*)(?:("|')(.*?)(?:\2|$)|(\S+))/g), matches,
taken = '', args = [], part;
cl = cl.trim();
while ((matches = reToken.exec(cl))) {
2015-04-17 11:08:22 +02:00
part = matches[3] || matches[4] || '';
if (matches[1]) {
2015-04-16 12:08:04 +02:00
args.push(taken);
taken = '';
}
taken += part;
}
if (taken) { args.push(taken); }
return args;
}
2015-04-17 11:08:22 +02:00
function toBool(res, options) {
return (
(options.trueValue.length &&
isMatched(res, options.trueValue, options.caseSensitive)) ? true :
(options.falseValue.length &&
isMatched(res, options.falseValue, options.caseSensitive)) ? false : res);
}
function getValidLine(options) {
var res, forceNext, limitMessage,
matches, histInput, args, resCheck;
2015-04-13 08:55:33 +02:00
function _getPhContent(param) { return getPhContent(param, options); }
2015-04-16 12:08:04 +02:00
function addDisplay(text)
{ options.display += (/[^\r\n]$/.test(options.display) ? '\n' : '') + text; }
2015-04-13 08:55:33 +02:00
2015-04-07 11:38:14 +02:00
options.limitSrc = options.limit;
options.displaySrc = options.display;
2015-04-05 13:05:23 +02:00
options.limit = ''; // for readlineExt
2015-04-13 08:55:33 +02:00
options.display = replacePlaceholder(options.display + '', _getPhContent);
2015-04-05 13:05:23 +02:00
while (true) {
res = _readlineSync(options);
2015-04-13 08:55:33 +02:00
forceNext = false;
limitMessage = '';
2015-04-16 12:08:04 +02:00
if (options.defaultInput && !res) { res = options.defaultInput; }
2015-04-13 08:55:33 +02:00
if (options.history) {
if ((matches = /^\s*\!(?:\!|-1)(:p)?\s*$/.exec(res))) { // `!!` `!-1` +`:p`
histInput = inputHistory[0] || '';
if (matches[1]) { forceNext = true; } // only display
else { res = histInput; } // replace input
// Show it even if it is empty (NL only).
2015-04-16 12:08:04 +02:00
addDisplay(histInput + '\n');
2015-04-13 08:55:33 +02:00
if (!forceNext) { // Loop may break
options.displayOnly = true;
_readlineSync(options);
options.displayOnly = false;
}
} else if (res && res !== inputHistory[inputHistory.length - 1]) {
inputHistory = [res];
}
}
2015-04-17 11:08:22 +02:00
if (!forceNext && options.cd && res) {
args = parseCl(res);
2015-04-16 12:08:04 +02:00
switch (args[0].toLowerCase()) {
case 'cd':
if (args[1]) {
try {
process.chdir(args[1].trim() === '~' ? (
IS_WIN ? (process.env.HOMEDRIVE || '') + (process.env.HOMEPATH || '') :
process.env.HOME || '') : args[1]);
} catch (e) {
addDisplay(e + '');
}
}
forceNext = true;
break;
case 'pwd':
addDisplay(process.cwd());
forceNext = true;
break;
}
}
2015-04-17 11:08:22 +02:00
if (!forceNext && options.preCheck) {
resCheck = options.preCheck(res, options);
2015-04-13 08:55:33 +02:00
res = resCheck.res;
if (resCheck.forceNext) { forceNext = true; } // Don't switch to false.
}
2015-04-16 12:08:04 +02:00
2015-04-13 08:55:33 +02:00
if (!forceNext) {
if (!options.limitSrc.length ||
isMatched(res, options.limitSrc, options.caseSensitive)) { break; }
if (options.limitMessage)
{ limitMessage = replacePlaceholder(options.limitMessage, _getPhContent); }
}
2015-04-16 12:08:04 +02:00
addDisplay((limitMessage ? limitMessage + '\n' : '') +
replacePlaceholder(options.displaySrc + '', _getPhContent));
2015-04-05 13:05:23 +02:00
}
2015-04-13 08:55:33 +02:00
return toBool(res, options);
2015-04-05 13:05:23 +02:00
}
// for dev
exports._DBG_set_useExt = function(val) { _DBG_useExt = val; };
exports._DBG_set_checkOptions = function(val) { _DBG_checkOptions = val; };
exports._DBG_set_checkMethod = function(val) { _DBG_checkMethod = val; };
2015-04-13 08:55:33 +02:00
exports._DBG_clearHistory = function() { lastInput = ''; inputHistory = []; };
2013-08-29 19:26:22 +02:00
2015-04-07 11:38:14 +02:00
exports.setDefault = function(options) {
defaultOptions = margeOptions(true, options);
return margeOptions(true); // copy
};
2015-04-13 08:55:33 +02:00
// ------------------------------------
2014-07-12 00:37:25 +02:00
exports.prompt = function(options) {
2015-04-13 08:55:33 +02:00
var readOptions = margeOptions(true, options);
2015-04-05 13:05:23 +02:00
readOptions.display = readOptions.prompt;
2015-04-14 18:05:24 +02:00
return getValidLine(readOptions);
2013-08-29 19:26:22 +02:00
};
2014-07-12 00:37:25 +02:00
exports.question = function(query, options) {
2015-04-14 18:05:24 +02:00
return getValidLine(margeOptions(margeOptions(true, options), {
2015-04-07 11:38:14 +02:00
display: query
2015-04-13 08:55:33 +02:00
}));
2013-08-29 19:26:22 +02:00
};
2015-03-01 15:46:52 +01:00
2015-03-07 16:19:40 +01:00
exports.keyIn = function(query, options) {
var readOptions = margeOptions(margeOptions(true, options), {
2015-04-07 11:38:14 +02:00
display: query,
keyIn: true,
keepWhitespace: true
2015-04-13 08:55:33 +02:00
});
2015-04-07 11:38:14 +02:00
// char list
readOptions.limitSrc = readOptions.limit.filter(function(value) {
var type = typeof value;
return type === 'string' || type === 'number';
})
2015-04-13 08:55:33 +02:00
.map(function(text) { return replacePlaceholder(text + '', getPhCharlist); });
2015-04-07 11:38:14 +02:00
// pattern
readOptions.limit = readOptions.limitSrc.join('').replace(/[^A-Za-z0-9_ ]/g, '\\$&');
2015-04-07 11:38:14 +02:00
['trueValue', 'falseValue'].forEach(function(optionName) {
var comps = [];
readOptions[optionName].forEach(function(comp) {
var type = typeof comp;
if (type === 'string' || type === 'number') {
comps = comps.concat((comp + '').split(''));
} else if (comp instanceof RegExp) {
comps.push(comp);
}
});
readOptions[optionName] = comps;
});
2015-04-07 11:38:14 +02:00
readOptions.display = replacePlaceholder(readOptions.display + '',
2015-04-13 08:55:33 +02:00
function(param) { return getPhContent(param, readOptions); });
2015-04-05 07:45:42 +02:00
2015-04-13 08:55:33 +02:00
return toBool(_readlineSync(readOptions), readOptions);
2015-03-01 15:46:52 +01:00
};
2015-04-05 07:45:42 +02:00
// ------------------------------------
exports.questionEMail = function(query, options) {
2015-04-13 08:55:33 +02:00
/* jshint eqnull:true */
if (query == null) { query = 'Input e-mail address :'; }
2015-04-13 08:55:33 +02:00
/* jshint eqnull:false */
return exports.question(query, margeOptions({
// -------- default
hideEchoBack: false,
// http://www.w3.org/TR/html5/forms.html#valid-e-mail-address
limit: /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,
limitMessage: 'Input valid e-mail address, please.',
trueValue: null,
falseValue: null
}, options, {
// -------- forced
keepWhitespace: false,
2015-04-14 18:05:24 +02:00
cd: false
}));
};
exports.questionNewPassword = function(query, options) {
var readOptions = margeOptions({
// -------- default
hideEchoBack: true,
mask: '*',
2015-04-13 08:55:33 +02:00
limitMessage: 'It can include: ${charlist}\n' +
'The length able to be: ${length}',
trueValue: null,
falseValue: null,
2015-04-13 08:55:33 +02:00
caseSensitive: true
2015-04-14 18:05:24 +02:00
}, options, {
// -------- forced
history: false,
cd: false,
// limit (by charlist etc.),
phContent: function(param) {
return param === 'charlist' ? resCharlist.text :
param === 'length' ? min + '...' + max : null;
}
}),
2015-04-16 12:08:04 +02:00
// added: charlist, min, max, confirmMessage, unmatchMessage
charlist, min, max, confirmMessage, unmatchMessage,
limit, resCharlist, limitMessage, res1, res2;
options = options || {};
2015-04-13 08:55:33 +02:00
2015-04-14 18:05:24 +02:00
charlist = replacePlaceholder(
2015-04-16 12:08:04 +02:00
options.charlist ? options.charlist + '' : '${!-~}', getPhCharlist);
if (isNaN(min = parseInt(options.min, 10)) || typeof min !== 'number') { min = 12; }
if (isNaN(max = parseInt(options.max, 10)) || typeof max !== 'number') { max = 24; }
2015-04-14 18:05:24 +02:00
limit = new RegExp('^[' + charlist.replace(/[^A-Za-z0-9_ ]/g, '\\$&') +
']{' + min + ',' + max + '}$');
resCharlist = array2charlist([charlist], readOptions.caseSensitive, true);
resCharlist.text = joinChunks(resCharlist.values, resCharlist.suppressed);
2015-04-13 08:55:33 +02:00
/* jshint eqnull:true */
2015-04-16 12:08:04 +02:00
confirmMessage = options.confirmMessage != null ? options.confirmMessage :
2015-04-13 08:55:33 +02:00
'Reinput same one to confirm it :';
2015-04-16 12:08:04 +02:00
unmatchMessage = options.unmatchMessage != null ? options.unmatchMessage :
'It differs from first one.' +
' Hit only Enter key if you want to retry from first one.';
2015-04-13 08:55:33 +02:00
/* jshint eqnull:false */
2015-04-14 18:05:24 +02:00
/* jshint eqnull:true */
if (query == null) { query = 'Input new password :'; }
/* jshint eqnull:false */
2015-04-14 18:05:24 +02:00
limitMessage = readOptions.limitMessage;
while (!res2) {
2015-04-14 18:05:24 +02:00
readOptions.limit = limit;
readOptions.limitMessage = limitMessage;
res1 = exports.question(query, readOptions);
readOptions.limit = [res1, ''];
2015-04-16 12:08:04 +02:00
readOptions.limitMessage = unmatchMessage;
res2 = exports.question(confirmMessage, readOptions);
}
return res1;
};
2015-04-14 18:05:24 +02:00
function _questionNum(query, options, parser) {
2015-04-13 08:55:33 +02:00
var validValue;
function getValidValue(value) {
2015-04-14 18:05:24 +02:00
validValue = parser(value);
2015-04-13 08:55:33 +02:00
return !isNaN(validValue) && typeof validValue === 'number';
}
2015-04-14 18:05:24 +02:00
exports.question(query, margeOptions({
// -------- default
limitMessage: 'Input valid number, please.'
}, options, {
2015-04-13 08:55:33 +02:00
// -------- forced
2015-04-14 18:05:24 +02:00
limit: getValidValue,
cd: false
2015-04-13 08:55:33 +02:00
// trueValue, falseValue are don't work.
}));
return validValue;
}
exports.questionInt = function(query, options) {
2015-04-14 18:05:24 +02:00
return _questionNum(query, options, function(value) { return parseInt(value, 10); });
};
exports.questionFloat = function(query, options) {
return _questionNum(query, options, parseFloat);
2015-04-13 08:55:33 +02:00
};
exports.questionPath = function(query, options) {
2015-04-14 18:05:24 +02:00
var readOptions = margeOptions({
// -------- default
2015-04-16 12:08:04 +02:00
hideEchoBack: false,
limitMessage: '${error(\n)}Input valid path, please.' +
'${( Min:)minSize}${( Max:)maxSize}',
2015-04-14 18:05:24 +02:00
history: true,
cd: true
}, options, {
2015-04-13 08:55:33 +02:00
// -------- forced
2015-04-14 18:05:24 +02:00
keepWhitespace: false,
limit: function(value) {
2015-04-16 12:08:04 +02:00
var exists, stat, res, pathUtil = require('path');
// mkdir -p
function mkdirParents(dirPath) {
dirPath.split(/\/|\\/).reduce(function(parents, dir) {
var path = pathUtil.resolve((parents += dir + pathUtil.sep));
if (!fs.existsSync(path)) {
fs.mkdirSync(path);
} else if (!fs.statSync(path).isDirectory()) {
throw new Error('Non directory already exists: ' + path);
}
return parents;
}, '');
}
try {
exists = fs.existsSync(value);
validPath = exists ? fs.realpathSync(value) : pathUtil.resolve(value);
// options.exists default: true, not-bool: no-check
if (!options.hasOwnProperty('exists') && !exists ||
typeof options.exists === 'boolean' && options.exists !== exists) {
error = (exists ? 'Already exists' : 'No such file or directory') +
': ' + validPath;
return;
}
if (!exists && options.create) {
if (options.isDirectory) {
mkdirParents(validPath);
} else {
mkdirParents(pathUtil.dirname(validPath));
fs.closeSync(fs.openSync(validPath, 'w')); // touch
}
validPath = fs.realpathSync(validPath);
}
if (exists && (options.minSize || options.maxSize ||
options.isFile || options.isDirectory)) {
2015-04-14 18:05:24 +02:00
stat = fs.statSync(validPath);
2015-04-16 12:08:04 +02:00
// type check first (directory has zero size)
if (options.isFile && !stat.isFile()) {
error = 'Not file: ' + validPath;
return;
} else if (options.isDirectory && !stat.isDirectory()) {
error = 'Not directory: ' + validPath;
return;
} else if (options.minSize && stat.size < +options.minSize ||
options.maxSize && stat.size > +options.maxSize) {
error = 'Size ' + stat.size +' is out of range: ' + validPath;
return;
}
}
if (typeof options.validate === 'function' &&
(res = options.validate(validPath)) !== true) {
error = res + '';
return;
2015-04-14 18:05:24 +02:00
}
2015-04-16 12:08:04 +02:00
} catch (e) {
error = e + '';
return;
2015-04-14 18:05:24 +02:00
}
return true;
},
2015-04-13 08:55:33 +02:00
// trueValue, falseValue are don't work.
2015-04-14 18:05:24 +02:00
phContent: function(param) {
2015-04-16 12:08:04 +02:00
return param === 'error' ? error :
param !== 'minSize' && param !== 'maxSize' ? null :
options.hasOwnProperty(param) ? options[param] + '' : '';
2015-04-14 18:05:24 +02:00
}
}),
2015-04-16 12:08:04 +02:00
// added: exists, create, minSize, maxSize, isFile, isDirectory, validate
validPath, error = '';
options = options || {};
2015-04-14 18:05:24 +02:00
/* jshint eqnull:true */
if (query == null) { query = 'Input path (you can "cd" and "pwd") :'; }
/* jshint eqnull:false */
exports.question(query, readOptions);
2015-04-13 08:55:33 +02:00
return validPath;
};
2015-04-17 11:08:22 +02:00
// props: preCheck, args, hRes, limit
function getClHandler(commandHandler, options) {
var clHandler = {}, hIndex = {};
if (typeof commandHandler === 'object') {
Object.keys(commandHandler).forEach(function(cmd) {
if (typeof commandHandler[cmd] === 'function') {
hIndex[options.caseSensitive ? cmd : cmd.toLowerCase()] = commandHandler[cmd];
}
});
clHandler.preCheck = function(res) {
var cmdKey;
clHandler.args = parseCl(res);
cmdKey = clHandler.args[0] || '';
if (!options.caseSensitive) { cmdKey = cmdKey.toLowerCase(); }
clHandler.hRes =
hIndex.hasOwnProperty(cmdKey) ?
hIndex[cmdKey].apply(res, clHandler.args.slice(1)) :
hIndex.hasOwnProperty('_') ? hIndex._.apply(res, clHandler.args) : null;
return {res: res, forceNext: false};
};
if (!hIndex.hasOwnProperty('_')) {
clHandler.limit = function() { // It's called after preCheck.
var cmdKey = clHandler.args[0] || '';
if (!options.caseSensitive) { cmdKey = cmdKey.toLowerCase(); }
return hIndex.hasOwnProperty(cmdKey);
};
}
} else {
clHandler.preCheck = function(res) {
clHandler.args = parseCl(res);
clHandler.hRes = typeof commandHandler === 'function' ?
commandHandler.apply(res, clHandler.args) : null;
return {res: res, forceNext: false};
};
}
return clHandler;
}
exports.promptCL = function(commandHandler, options) {
var readOptions = margeOptions({
2015-04-13 08:55:33 +02:00
// -------- default
2015-04-16 12:08:04 +02:00
hideEchoBack: false,
2015-04-17 11:08:22 +02:00
limitMessage: 'Requested command is not available.',
caseSensitive: false,
2015-04-14 18:05:24 +02:00
history: true
2015-04-17 11:08:22 +02:00
}, options),
2015-04-14 18:05:24 +02:00
// -------- forced
2015-04-17 11:08:22 +02:00
// trueValue, falseValue are don't work.
// preCheck, limit (by clHandler)
clHandler = getClHandler(commandHandler, readOptions);
readOptions.limit = clHandler.limit;
readOptions.preCheck = clHandler.preCheck;
exports.prompt(readOptions);
return clHandler.args;
2015-04-13 08:55:33 +02:00
};
2015-04-17 11:08:22 +02:00
exports.promptLoop = function(inputHandler, options) {
var readOptions = margeOptions({
// -------- default
hideEchoBack: false,
trueValue: null,
falseValue: null,
caseSensitive: false,
history: true
}, options);
while (true) { if (inputHandler(exports.prompt(readOptions))) { break; } }
return;
};
exports.promptCLLoop = function(commandHandler, options) {
var readOptions = margeOptions({
// -------- default
hideEchoBack: false,
limitMessage: 'Requested command is not available.',
caseSensitive: false,
history: true
}, options),
// -------- forced
// trueValue, falseValue are don't work.
// preCheck, limit (by clHandler)
clHandler = getClHandler(commandHandler, readOptions);
readOptions.limit = clHandler.limit;
readOptions.preCheck = clHandler.preCheck;
while (true) {
exports.prompt(readOptions);
if (clHandler.hRes) { break; }
}
return;
};
exports.promptSimShell = function(options) {
2015-04-16 12:08:04 +02:00
return exports.prompt(margeOptions({
// -------- default
hideEchoBack: false,
history: true
}, options, {
// -------- forced
prompt: (function() {
return IS_WIN ?
'${cwd}>' :
// 'user@host:cwd$ '
(process.env.USER || '') +
(process.env.HOSTNAME ?
'@' + process.env.HOSTNAME.replace(/\..*$/, '') : '') +
':${cwdHome}$ ';
})()
}));
};
function _keyInYN(query, options, limit) {
2015-04-14 18:05:24 +02:00
var res;
/* jshint eqnull:true */
if (query == null) { query = 'Are you sure? :'; }
/* jshint eqnull:false */
if ((!options || options.guide !== false) && (query += ''))
{ query = query.replace(/\s*:?\s*$/, '') + ' [y/n] :'; }
res = exports.keyIn(query, margeOptions(options, {
// -------- forced
hideEchoBack: false,
2015-04-16 12:08:04 +02:00
limit: limit,
trueValue: 'y',
2015-04-13 08:55:33 +02:00
falseValue: 'n',
caseSensitive: false
2015-04-14 18:05:24 +02:00
}));
2015-04-16 12:08:04 +02:00
// added: guide
2015-04-13 08:55:33 +02:00
return typeof res === 'boolean' ? res : '';
2015-04-16 12:08:04 +02:00
}
exports.keyInYN = function(query, options) { return _keyInYN(query, options); };
exports.keyInYNStrict = function(query, options)
{ return _keyInYN(query, options, 'yn'); };
exports.keyInPause = function(query, options) {
2015-04-13 08:55:33 +02:00
/* jshint eqnull:true */
if (query == null) { query = 'Continue...'; }
2015-04-13 08:55:33 +02:00
/* jshint eqnull:false */
2015-04-14 18:05:24 +02:00
if ((!options || options.guide !== false) && (query += ''))
{ query = query.replace(/\s+$/, '') + ' (Hit any key)'; }
2015-04-16 12:08:04 +02:00
exports.keyIn(query, margeOptions({
// -------- default
limit: null
}, options, {
2015-04-14 18:05:24 +02:00
// -------- forced
hideEchoBack: true,
mask: ''
}));
2015-04-16 12:08:04 +02:00
// added: guide
return;
};
2015-04-17 11:08:22 +02:00
exports.keyInSelect = function(items, query, options) {
var readOptions = margeOptions({
// -------- default
2015-04-14 18:05:24 +02:00
hideEchoBack: false
}, options, {
// -------- forced
trueValue: null,
2015-04-13 08:55:33 +02:00
falseValue: null,
caseSensitive: false
2015-04-14 18:05:24 +02:00
// limit (by items)
}),
2015-04-16 12:08:04 +02:00
// added: guide, cancel
2015-04-14 18:05:24 +02:00
keylist = '', key2i = {}, charCode = 49 /* '1' */, display = '\n';
if (!Array.isArray(items) || items.length > 35)
{ throw '`items` must be Array (max length: 35).'; }
items.forEach(function(item, i) {
var key = String.fromCharCode(charCode);
keylist += key;
key2i[key] = i;
display += '[' + key + '] ' + item.trim() + '\n';
2015-04-14 18:05:24 +02:00
charCode = charCode === 57 /* '9' */ ? 97 /* 'a' */ : charCode + 1;
});
2015-04-14 18:05:24 +02:00
if (!options || options.cancel !== false) {
keylist += '0';
key2i['0'] = -1;
display += '[' + '0' + '] CANCEL\n';
}
readOptions.limit = keylist;
display += '\n';
2015-04-13 08:55:33 +02:00
/* jshint eqnull:true */
if (query == null) { query = 'Choose one from list :'; }
2015-04-13 08:55:33 +02:00
/* jshint eqnull:false */
if ((query += '')) {
2015-04-14 18:05:24 +02:00
if (!options || options.guide !== false)
{ query = query.replace(/\s*:?\s*$/, '') + ' [${limit}] :'; }
display += query;
}
2015-04-14 18:05:24 +02:00
return key2i[exports.keyIn(display, readOptions).toLowerCase()];
};
2015-04-07 11:38:14 +02:00
// ======== DEPRECATED ========
function _setOption(optionName, args) {
var options;
if (args.length) { options = {}; options[optionName] = args[0]; }
return exports.setDefault(options)[optionName];
}
2015-04-07 11:38:14 +02:00
exports.setPrint = function() { return _setOption('print', arguments); };
exports.setPrompt = function() { return _setOption('prompt', arguments); };
exports.setEncoding = function() { return _setOption('encoding', arguments); };
exports.setMask = function() { return _setOption('mask', arguments); };
exports.setBufferSize = function() { return _setOption('bufferSize', arguments); };