Code style for ESLint

This commit is contained in:
anseki 2016-04-27 22:02:12 +09:00
parent 2b0e8cd93f
commit 08e130af38
3 changed files with 450 additions and 421 deletions

8
.eslintrc Normal file
View file

@ -0,0 +1,8 @@
{
"extends": "../../../_common/eslintrc.json",
"env": {"node": true},
"rules": {
"no-underscore-dangle": [2, {"allow": ["_DBG_useExt", "_DBG_checkOptions", "_DBG_checkMethod", "_readlineSync", "_execFileSync", "_handle", "_flattenArray", "_getPhContent", "_DBG_set_useExt", "_DBG_set_checkOptions", "_DBG_set_checkMethod", "_DBG_clearHistory", "_questionNum", "_keyInYN", "_setOption"]}],
"camelcase": 0
}
}

1
.gitignore vendored
View file

@ -1,3 +1,4 @@
.vscode
node_modules node_modules
npm-debug.log npm-debug.log
tmp tmp

View file

@ -21,6 +21,7 @@ var
pathUtil = require('path'), pathUtil = require('path'),
defaultOptions = { defaultOptions = {
/* eslint-disable key-spacing */
prompt: '> ', prompt: '> ',
hideEchoBack: false, hideEchoBack: false,
mask: '*', mask: '*',
@ -38,6 +39,7 @@ var
cd: false, cd: false,
phContent: void 0, phContent: void 0,
preCheck: void 0 preCheck: void 0
/* eslint-enable key-spacing */
}, },
fdR = 'none', fdW, ttyR, isRawMode = false, fdR = 'none', fdW, ttyR, isRawMode = false,
@ -45,6 +47,188 @@ var
lastInput = '', inputHistory = [], lastInput = '', inputHistory = [],
_DBG_useExt = false, _DBG_checkOptions = false, _DBG_checkMethod = false; _DBG_useExt = false, _DBG_checkOptions = false, _DBG_checkMethod = false;
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) {
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]));
}
}
});
return args;
})({
/* eslint-disable key-spacing */
display: 'string',
displayOnly: 'boolean',
keyIn: 'boolean',
hideEchoBack: 'boolean',
mask: 'string',
limit: 'string',
caseSensitive: 'boolean'
/* eslint-enable key-spacing */
}));
}
// piping via files (for Node v0.10-)
function _execFileSync(options, execOptions) {
function getTempfile(name) {
var filepath, suffix = '', fd;
tempdir = tempdir || require('os').tmpdir();
while (true) {
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, extMessage,
pathStdout = getTempfile('readline-sync.stdout'),
pathStderr = getTempfile('readline-sync.stderr'),
pathExit = getTempfile('readline-sync.exit'),
pathDone = getTempfile('readline-sync.done'),
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);
if (IS_WIN) {
shellPath = process.env.ComSpec || 'cmd.exe';
process.env.Q = '"'; // The quote (") that isn't escaped.
// `()` for ignore space by echo
shellArgs = ['/V:ON', '/S', '/C',
'(%Q%' + shellPath + '%Q% /V:ON /S /C %Q%' + /* ESLint bug? */ // eslint-disable-line no-path-concat
'%Q%' + extHostPath + '%Q%' +
hostArgs.map(function(arg) { return ' %Q%' + arg + '%Q%'; }).join('') +
' & (echo !ERRORLEVEL!)>%Q%' + pathExit + '%Q%%Q%) 2>%Q%' + pathStderr + '%Q%' +
' |%Q%' + process.execPath + '%Q% %Q%' + __dirname + '\\encrypt.js%Q%' +
' %Q%' + ALGORITHM_CIPHER + '%Q% %Q%' + password + '%Q%' +
' >%Q%' + pathStdout + '%Q%' +
' & (echo 1)>%Q%' + pathDone + '%Q%'];
} else {
shellPath = '/bin/sh';
shellArgs = ['-c',
// Use `()`, not `{}` for `-c` (text param)
'("' + extHostPath + '"' + /* ESLint bug? */ // eslint-disable-line no-path-concat
hostArgs.map(function(arg) { return " '" + arg.replace(/'/g, "'\\''") + "'"; }).join('') +
'; echo $?>"' + pathExit + '") 2>"' + pathStderr + '"' +
' |"' + process.execPath + '" "' + __dirname + '/encrypt.js"' +
' "' + ALGORITHM_CIPHER + '" "' + password + '"' +
' >"' + pathStdout + '"' +
'; echo 1 >"' + pathDone + '"'];
}
if (_DBG_checkMethod) { _DBG_checkMethod('_execFileSync', hostArgs); }
try {
childProc.spawn(shellPath, shellArgs, execOptions);
} catch (e) {
res.error = new Error(e.message);
res.error.method = '_execFileSync - spawn';
res.error.program = shellPath;
res.error.args = shellArgs;
}
while (fs.readFileSync(pathDone, {encoding: options.encoding}).trim() !== '1') {} // eslint-disable-line no-empty
if ((exitCode =
fs.readFileSync(pathExit, {encoding: options.encoding}).trim()) === '0') {
res.input =
decipher.update(fs.readFileSync(pathStdout, {encoding: 'binary'}),
'hex', options.encoding) +
decipher.final(options.encoding);
} else {
extMessage = fs.readFileSync(pathStderr, {encoding: options.encoding}).trim();
res.error = new Error(DEFAULT_ERR_MSG + (extMessage ? '\n' + extMessage : ''));
res.error.method = '_execFileSync';
res.error.program = shellPath;
res.error.args = shellArgs;
res.error.extMessage = extMessage;
res.error.exitCode = +exitCode;
}
fs.unlinkSync(pathStdout);
fs.unlinkSync(pathStderr);
fs.unlinkSync(pathExit);
fs.unlinkSync(pathDone);
return res;
}
function readlineExt(options) {
var hostArgs, res = {}, extMessage,
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']; // eslint-disable-line no-path-concat
} else { // Windows Script Host
extHostPath = 'cscript.exe';
extHostArgs = ['//nologo', __dirname + '\\read.cs.js']; // eslint-disable-line no-path-concat
}
} else {
extHostPath = '/bin/sh';
extHostArgs = [__dirname + '/read.sh']; // eslint-disable-line no-path-concat
}
}
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); }
try {
res.input = childProc.execFileSync(extHostPath, hostArgs, execOptions);
} catch (e) { // non-zero exit code
extMessage = e.stderr ? (e.stderr + '').trim() : '';
res.error = new Error(DEFAULT_ERR_MSG + (extMessage ? '\n' + extMessage : ''));
res.error.method = 'execFileSync';
res.error.program = extHostPath;
res.error.args = hostArgs;
res.error.extMessage = extMessage;
res.error.exitCode = e.status;
res.error.code = e.code;
res.error.signal = e.signal;
}
} else {
res = _execFileSync(options, execOptions);
}
if (!res.error) {
res.input = res.input.replace(/^\s*'|'\s*$/g, '');
options.display = '';
}
return res;
}
/* /*
display: string display: string
displayOnly: boolean displayOnly: boolean
@ -107,7 +291,7 @@ function _readlineSync(options) {
// 'CONIN$' might fail on XP, 2000, 7 (x86). // 'CONIN$' might fail on XP, 2000, 7 (x86).
fdR = getFsB().open('CONIN$', constants.O_RDWR, parseInt('0666', 8)); fdR = getFsB().open('CONIN$', constants.O_RDWR, parseInt('0666', 8));
ttyR = new TTY(fdR, true); ttyR = new TTY(fdR, true);
} catch (e) {} } catch (e) { /* ignore */ }
} }
if (process.stdout.isTTY) { if (process.stdout.isTTY) {
@ -115,11 +299,11 @@ function _readlineSync(options) {
} else { } else {
try { try {
fdW = fs.openSync('\\\\.\\CON', 'w'); fdW = fs.openSync('\\\\.\\CON', 'w');
} catch (e) {} } catch (e) { /* ignore */ }
if (typeof fdW !== 'number') { // Retry if (typeof fdW !== 'number') { // Retry
try { try {
fdW = getFsB().open('CONOUT$', constants.O_RDWR, parseInt('0666', 8)); fdW = getFsB().open('CONOUT$', constants.O_RDWR, parseInt('0666', 8));
} catch (e) {} } catch (e) { /* ignore */ }
} }
} }
@ -129,13 +313,13 @@ function _readlineSync(options) {
try { try {
fdR = fs.openSync('/dev/tty', 'r'); // device file, not process.stdin fdR = fs.openSync('/dev/tty', 'r'); // device file, not process.stdin
ttyR = process.stdin._handle; ttyR = process.stdin._handle;
} catch (e) {} } catch (e) { /* ignore */ }
} else { } else {
// Node v0.12 read() fails. // Node v0.12 read() fails.
try { try {
fdR = fs.openSync('/dev/tty', 'r'); fdR = fs.openSync('/dev/tty', 'r');
ttyR = new TTY(fdR, false); ttyR = new TTY(fdR, false);
} catch (e) {} } catch (e) { /* ignore */ }
} }
if (process.stdout.isTTY) { if (process.stdout.isTTY) {
@ -143,7 +327,7 @@ function _readlineSync(options) {
} else { } else {
try { try {
fdW = fs.openSync('/dev/tty', 'w'); fdW = fs.openSync('/dev/tty', 'w');
} catch (e) {} } catch (e) { /* ignore */ }
} }
} }
})(); })();
@ -236,195 +420,16 @@ function _readlineSync(options) {
(lastInput = options.keepWhitespace || options.keyIn ? input : input.trim()); (lastInput = options.keepWhitespace || options.keyIn ? input : input.trim());
} }
function readlineExt(options) {
var hostArgs, res = {}, extMessage,
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'];
}
}
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); }
try {
res.input = childProc.execFileSync(extHostPath, hostArgs, execOptions);
} catch (e) { // non-zero exit code
extMessage = e.stderr ? (e.stderr + '').trim() : '';
res.error = new Error(DEFAULT_ERR_MSG + (extMessage ? '\n' + extMessage : ''));
res.error.method = 'execFileSync';
res.error.program = extHostPath;
res.error.args = hostArgs;
res.error.extMessage = extMessage;
res.error.exitCode = e.status;
res.error.code = e.code;
res.error.signal = e.signal;
}
} else {
res = _execFileSync(options, execOptions);
}
if (!res.error) {
res.input = res.input.replace(/^\s*'|'\s*$/g, '');
options.display = '';
}
return res;
}
// piping via files (for Node v0.10-)
function _execFileSync(options, execOptions) {
function getTempfile(name) {
var filepath, suffix = '', fd;
tempdir = tempdir || require('os').tmpdir();
while (true) {
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, extMessage,
pathStdout = getTempfile('readline-sync.stdout'),
pathStderr = getTempfile('readline-sync.stderr'),
pathExit = getTempfile('readline-sync.exit'),
pathDone = getTempfile('readline-sync.done'),
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);
if (IS_WIN) {
shellPath = process.env.ComSpec || 'cmd.exe';
process.env.Q = '"'; // The quote (") that isn't escaped.
// `()` 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('') +
' & (echo !ERRORLEVEL!)>%Q%' + pathExit + '%Q%%Q%) 2>%Q%' + pathStderr + '%Q%' +
' |%Q%' + process.execPath + '%Q% %Q%' + __dirname + '\\encrypt.js%Q%' +
' %Q%' + ALGORITHM_CIPHER + '%Q% %Q%' + password + '%Q%' +
' >%Q%' + pathStdout + '%Q%' +
' & (echo 1)>%Q%' + pathDone + '%Q%'];
} else {
shellPath = '/bin/sh';
shellArgs = ['-c',
// Use `()`, not `{}` for `-c` (text param)
'("' + extHostPath + '"' +
hostArgs.map(function(arg)
{ return " '" + arg.replace(/'/g, "'\\''") + "'"; }).join('') +
'; echo $?>"' + pathExit + '") 2>"' + pathStderr + '"' +
' |"' + process.execPath + '" "' + __dirname + '/encrypt.js"' +
' "' + ALGORITHM_CIPHER + '" "' + password + '"' +
' >"' + pathStdout + '"' +
'; echo 1 >"' + pathDone + '"'];
}
if (_DBG_checkMethod) { _DBG_checkMethod('_execFileSync', hostArgs); }
try {
childProc.spawn(shellPath, shellArgs, execOptions);
} catch (e) {
res.error = new Error(e.message);
res.error.method = '_execFileSync - spawn';
res.error.program = shellPath;
res.error.args = shellArgs;
}
while (fs.readFileSync(pathDone, {encoding: options.encoding}).trim() !== '1') {}
if ((exitCode =
fs.readFileSync(pathExit, {encoding: options.encoding}).trim()) === '0') {
res.input =
decipher.update(fs.readFileSync(pathStdout, {encoding: 'binary'}),
'hex', options.encoding) +
decipher.final(options.encoding);
} else {
extMessage = fs.readFileSync(pathStderr, {encoding: options.encoding}).trim();
res.error = new Error(DEFAULT_ERR_MSG + (extMessage ? '\n' + extMessage : ''));
res.error.method = '_execFileSync';
res.error.program = shellPath;
res.error.args = shellArgs;
res.error.extMessage = extMessage;
res.error.exitCode = +exitCode;
}
fs.unlinkSync(pathStdout);
fs.unlinkSync(pathStderr);
fs.unlinkSync(pathExit);
fs.unlinkSync(pathDone);
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) {
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]));
}
}
});
return args;
})({
display: 'string',
displayOnly: 'boolean',
keyIn: 'boolean',
hideEchoBack: 'boolean',
mask: 'string',
limit: 'string',
caseSensitive: 'boolean'
}));
}
function flattenArray(array, validator) { function flattenArray(array, validator) {
var flatArray = []; var flatArray = [];
function _flattenArray(array) { function _flattenArray(array) {
/* jshint eqnull:true */ if (array == null) { // eslint-disable-line eqeqeq
if (array == null) { return; } return;
/* jshint eqnull:false */ } else if (Array.isArray(array)) {
else if (Array.isArray(array)) { array.forEach(_flattenArray); } array.forEach(_flattenArray);
else if (!validator || validator(array)) { flatArray.push(array); } } else if (!validator || validator(array)) {
flatArray.push(array);
}
} }
_flattenArray(array); _flattenArray(array);
return flatArray; return flatArray;
@ -451,9 +456,7 @@ function margeOptions() {
} }
return optionsList.reduce(function(options, optionsPart) { return optionsList.reduce(function(options, optionsPart) {
/* jshint eqnull:true */ if (optionsPart == null) { return options; } // eslint-disable-line eqeqeq
if (optionsPart == null) { return options; }
/* jshint eqnull:false */
// ======== DEPRECATED ======== // ======== DEPRECATED ========
if (optionsPart.hasOwnProperty('noEchoBack') && if (optionsPart.hasOwnProperty('noEchoBack') &&
@ -473,24 +476,22 @@ function margeOptions() {
var value; var value;
if (!optionsPart.hasOwnProperty(optionName)) { return; } if (!optionsPart.hasOwnProperty(optionName)) { return; }
value = optionsPart[optionName]; value = optionsPart[optionName];
switch (optionName) { switch (optionName) { // eslint-disable-line default-case
// _readlineSync <- * * -> defaultOptions // _readlineSync <- * * -> defaultOptions
// ================ string // ================ string
case 'mask': // * * case 'mask': // * *
case 'limitMessage': // * case 'limitMessage': // *
case 'defaultInput': // * case 'defaultInput': // *
case 'encoding': // * * case 'encoding': // * *
/* jshint eqnull:true */ value = value != null ? value + '' : ''; // eslint-disable-line eqeqeq
value = value != null ? value + '' : ''; if (value && optionName !== 'limitMessage') { value = value.replace(/[\r\n]/g, ''); }
/* jshint eqnull:false */
if (value && optionName !== 'limitMessage')
{ value = value.replace(/[\r\n]/g, ''); }
options[optionName] = value; options[optionName] = value;
break; break;
// ================ number(int) // ================ number(int)
case 'bufferSize': // * * case 'bufferSize': // * *
if (!isNaN(value = parseInt(value, 10)) && typeof value === 'number') if (!isNaN(value = parseInt(value, 10)) && typeof value === 'number') {
{ options[optionName] = value; } // limited updating (number is needed) options[optionName] = value; // limited updating (number is needed)
}
break; break;
// ================ boolean // ================ boolean
case 'displayOnly': // * case 'displayOnly': // *
@ -523,9 +524,7 @@ function margeOptions() {
// ================ other // ================ other
case 'prompt': // * case 'prompt': // *
case 'display': // * case 'display': // *
/* jshint eqnull:true */ options[optionName] = value != null ? value : ''; // eslint-disable-line eqeqeq
options[optionName] = value != null ? value : '';
/* jshint eqnull:false */
break; break;
} }
}); });
@ -581,8 +580,8 @@ function array2charlist(array, caseSensitive, collectSymbols) {
return groups; return groups;
} }
values = array.reduce(function(chars, value) values = array.reduce(
{ return chars.concat((value + '').split('')); }, []) function(chars, value) { return chars.concat((value + '').split('')); }, [])
.reduce(function(groups, curChar) { .reduce(function(groups, curChar) {
var curGroupClass, curCharCode; var curGroupClass, curCharCode;
if (!caseSensitive) { curChar = curChar.toLowerCase(); } if (!caseSensitive) { curChar = curChar.toLowerCase(); }
@ -609,8 +608,9 @@ function array2charlist(array, caseSensitive, collectSymbols) {
return {values: values, suppressed: suppressed}; return {values: values, suppressed: suppressed};
} }
function joinChunks(chunks, suppressed) function joinChunks(chunks, suppressed) {
{ return chunks.join(chunks.length > 2 ? ', ' : suppressed ? ' / ' : '/'); } return chunks.join(chunks.length > 2 ? ', ' : suppressed ? ' / ' : '/');
}
function getPhContent(param, options) { function getPhContent(param, options) {
var text, values, resCharlist = {}, arg; var text, values, resCharlist = {}, arg;
@ -665,8 +665,11 @@ function getPhContent(param, options) {
case 'CWD': case 'CWD':
case 'cwdHome': case 'cwdHome':
text = process.cwd(); text = process.cwd();
if (param === 'CWD') { text = pathUtil.basename(text); } if (param === 'CWD') {
else if (param === 'cwdHome') { text = replaceHomePath(text); } text = pathUtil.basename(text);
} else if (param === 'cwdHome') {
text = replaceHomePath(text);
}
break; break;
case 'date': case 'date':
case 'time': case 'time':
@ -687,12 +690,11 @@ function getPhContent(param, options) {
function getPhCharlist(param) { function getPhCharlist(param) {
var matches = /^(.)-(.)$/.exec(param), text = '', from, to, code, step; var matches = /^(.)-(.)$/.exec(param), text = '', from, to, code, step;
if (!matches) { return; } if (!matches) { return null; }
from = matches[1].charCodeAt(0); from = matches[1].charCodeAt(0);
to = matches[2].charCodeAt(0); to = matches[2].charCodeAt(0);
step = from < to ? 1 : -1; step = from < to ? 1 : -1;
for (code = from; code !== to + step; code += step) for (code = from; code !== to + step; code += step) { text += String.fromCharCode(code); } /* ESLint bug */ // eslint-disable-line no-unmodified-loop-condition
{ text += String.fromCharCode(code); }
return text; return text;
} }
@ -724,9 +726,9 @@ function toBool(res, options) {
function getValidLine(options) { function getValidLine(options) {
var res, forceNext, limitMessage, var res, forceNext, limitMessage,
matches, histInput, args, resCheck; matches, histInput, args, resCheck;
function _getPhContent(param) { return getPhContent(param, options); } function _getPhContent(param) { return getPhContent(param, options); }
function addDisplay(text) function addDisplay(text) { options.display += (/[^\r\n]$/.test(options.display) ? '\n' : '') + text; }
{ options.display += (/[^\r\n]$/.test(options.display) ? '\n' : '') + text; }
options.limitSrc = options.limit; options.limitSrc = options.limit;
options.displaySrc = options.display; options.displaySrc = options.display;
@ -743,8 +745,11 @@ function getValidLine(options) {
if (options.history) { if (options.history) {
if ((matches = /^\s*\!(?:\!|-1)(:p)?\s*$/.exec(res))) { // `!!` `!-1` +`:p` if ((matches = /^\s*\!(?:\!|-1)(:p)?\s*$/.exec(res))) { // `!!` `!-1` +`:p`
histInput = inputHistory[0] || ''; histInput = inputHistory[0] || '';
if (matches[1]) { forceNext = true; } // only display if (matches[1]) { // only display
else { res = histInput; } // replace input forceNext = true;
} else { // replace input
res = histInput;
}
// Show it even if it is empty (NL only). // Show it even if it is empty (NL only).
addDisplay(histInput + '\n'); addDisplay(histInput + '\n');
if (!forceNext) { // Loop may break if (!forceNext) { // Loop may break
@ -759,7 +764,7 @@ function getValidLine(options) {
if (!forceNext && options.cd && res) { if (!forceNext && options.cd && res) {
args = parseCl(res); args = parseCl(res);
switch (args[0].toLowerCase()) { switch (args[0].toLowerCase()) { // eslint-disable-line default-case
case 'cd': case 'cd':
if (args[1]) { if (args[1]) {
try { try {
@ -786,8 +791,9 @@ function getValidLine(options) {
if (!forceNext) { if (!forceNext) {
if (!options.limitSrc.length || if (!options.limitSrc.length ||
isMatched(res, options.limitSrc, options.caseSensitive)) { break; } isMatched(res, options.limitSrc, options.caseSensitive)) { break; }
if (options.limitMessage) if (options.limitMessage) {
{ limitMessage = replacePlaceholder(options.limitMessage, _getPhContent); } limitMessage = replacePlaceholder(options.limitMessage, _getPhContent);
}
} }
addDisplay((limitMessage ? limitMessage + '\n' : '') + addDisplay((limitMessage ? limitMessage + '\n' : '') +
@ -810,9 +816,11 @@ exports.setDefaultOptions = function(options) {
}; };
exports.question = function(query, options) { exports.question = function(query, options) {
/* eslint-disable key-spacing */
return getValidLine(margeOptions(margeOptions(true, options), { return getValidLine(margeOptions(margeOptions(true, options), {
display: query display: query
})); }));
/* eslint-enable key-spacing */
}; };
exports.prompt = function(options) { exports.prompt = function(options) {
@ -822,11 +830,13 @@ exports.prompt = function(options) {
}; };
exports.keyIn = function(query, options) { exports.keyIn = function(query, options) {
/* eslint-disable key-spacing */
var readOptions = margeOptions(margeOptions(true, options), { var readOptions = margeOptions(margeOptions(true, options), {
display: query, display: query,
keyIn: true, keyIn: true,
keepWhitespace: true keepWhitespace: true
}); });
/* eslint-enable key-spacing */
// char list // char list
readOptions.limitSrc = readOptions.limit.filter(function(value) { readOptions.limitSrc = readOptions.limit.filter(function(value) {
@ -856,9 +866,8 @@ exports.keyIn = function(query, options) {
// ------------------------------------ // ------------------------------------
exports.questionEMail = function(query, options) { exports.questionEMail = function(query, options) {
/* jshint eqnull:true */ if (query == null) { query = 'Input e-mail address :'; } // eslint-disable-line eqeqeq
if (query == null) { query = 'Input e-mail address :'; } /* eslint-disable key-spacing */
/* jshint eqnull:false */
return exports.question(query, margeOptions({ return exports.question(query, margeOptions({
// -------- default // -------- default
hideEchoBack: false, hideEchoBack: false,
@ -872,10 +881,13 @@ exports.questionEMail = function(query, options) {
keepWhitespace: false, keepWhitespace: false,
cd: false cd: false
})); }));
/* eslint-enable key-spacing */
}; };
exports.questionNewPassword = function(query, options) { exports.questionNewPassword = function(query, options) {
var readOptions = margeOptions({ /* eslint-disable key-spacing */
var resCharlist, min, max,
readOptions = margeOptions({
// -------- default // -------- default
hideEchoBack: true, hideEchoBack: true,
mask: '*', mask: '*',
@ -895,8 +907,9 @@ exports.questionNewPassword = function(query, options) {
} }
}), }),
// added: charlist, min, max, confirmMessage, unmatchMessage // added: charlist, min, max, confirmMessage, unmatchMessage
charlist, min, max, confirmMessage, unmatchMessage, charlist, confirmMessage, unmatchMessage,
limit, resCharlist, limitMessage, res1, res2; limit, limitMessage, res1, res2;
/* eslint-enable key-spacing */
options = options || {}; options = options || {};
charlist = replacePlaceholder( charlist = replacePlaceholder(
@ -908,17 +921,13 @@ exports.questionNewPassword = function(query, options) {
resCharlist = array2charlist([charlist], readOptions.caseSensitive, true); resCharlist = array2charlist([charlist], readOptions.caseSensitive, true);
resCharlist.text = joinChunks(resCharlist.values, resCharlist.suppressed); resCharlist.text = joinChunks(resCharlist.values, resCharlist.suppressed);
/* jshint eqnull:true */ confirmMessage = options.confirmMessage != null ? options.confirmMessage : // eslint-disable-line eqeqeq
confirmMessage = options.confirmMessage != null ? options.confirmMessage :
'Reinput a same one to confirm it :'; 'Reinput a same one to confirm it :';
unmatchMessage = options.unmatchMessage != null ? options.unmatchMessage : unmatchMessage = options.unmatchMessage != null ? options.unmatchMessage : // eslint-disable-line eqeqeq
'It differs from first one.' + 'It differs from first one.' +
' Hit only the Enter key if you want to retry from first one.'; ' Hit only the Enter key if you want to retry from first one.';
/* jshint eqnull:false */
/* jshint eqnull:true */ if (query == null) { query = 'Input new password :'; } // eslint-disable-line eqeqeq
if (query == null) { query = 'Input new password :'; }
/* jshint eqnull:false */
limitMessage = readOptions.limitMessage; limitMessage = readOptions.limitMessage;
while (!res2) { while (!res2) {
@ -940,6 +949,7 @@ function _questionNum(query, options, parser) {
validValue = parser(value); validValue = parser(value);
return !isNaN(validValue) && typeof validValue === 'number'; return !isNaN(validValue) && typeof validValue === 'number';
} }
/* eslint-disable key-spacing */
exports.question(query, margeOptions({ exports.question(query, margeOptions({
// -------- default // -------- default
limitMessage: 'Input valid number, please.' limitMessage: 'Input valid number, please.'
@ -949,6 +959,7 @@ function _questionNum(query, options, parser) {
cd: false cd: false
// trueValue, falseValue, caseSensitive, keepWhitespace don't work. // trueValue, falseValue, caseSensitive, keepWhitespace don't work.
})); }));
/* eslint-enable key-spacing */
return validValue; return validValue;
} }
exports.questionInt = function(query, options) { exports.questionInt = function(query, options) {
@ -959,7 +970,9 @@ exports.questionFloat = function(query, options) {
}; };
exports.questionPath = function(query, options) { exports.questionPath = function(query, options) {
var readOptions = margeOptions({ /* eslint-disable key-spacing */
var validPath, error = '',
readOptions = margeOptions({
// -------- default // -------- default
hideEchoBack: false, hideEchoBack: false,
limitMessage: '$<error(\n)>Input valid path, please.' + limitMessage: '$<error(\n)>Input valid path, please.' +
@ -994,7 +1007,7 @@ exports.questionPath = function(query, options) {
typeof options.exists === 'boolean' && options.exists !== exists) { typeof options.exists === 'boolean' && options.exists !== exists) {
error = (exists ? 'Already exists' : 'No such file or directory') + error = (exists ? 'Already exists' : 'No such file or directory') +
': ' + validPath; ': ' + validPath;
return; return false;
} }
if (!exists && options.create) { if (!exists && options.create) {
if (options.isDirectory) { if (options.isDirectory) {
@ -1011,24 +1024,24 @@ exports.questionPath = function(query, options) {
// type check first (directory has zero size) // type check first (directory has zero size)
if (options.isFile && !stat.isFile()) { if (options.isFile && !stat.isFile()) {
error = 'Not file: ' + validPath; error = 'Not file: ' + validPath;
return; return false;
} else if (options.isDirectory && !stat.isDirectory()) { } else if (options.isDirectory && !stat.isDirectory()) {
error = 'Not directory: ' + validPath; error = 'Not directory: ' + validPath;
return; return false;
} else if (options.min && stat.size < +options.min || } else if (options.min && stat.size < +options.min ||
options.max && stat.size > +options.max) { options.max && stat.size > +options.max) {
error = 'Size ' + stat.size + ' is out of range: ' + validPath; error = 'Size ' + stat.size + ' is out of range: ' + validPath;
return; return false;
} }
} }
if (typeof options.validate === 'function' && if (typeof options.validate === 'function' &&
(res = options.validate(validPath)) !== true) { (res = options.validate(validPath)) !== true) {
if (typeof res === 'string') { error = res; } if (typeof res === 'string') { error = res; }
return; return false;
} }
} catch (e) { } catch (e) {
error = e + ''; error = e + '';
return; return false;
} }
return true; return true;
}, },
@ -1038,14 +1051,12 @@ exports.questionPath = function(query, options) {
param !== 'min' && param !== 'max' ? null : param !== 'min' && param !== 'max' ? null :
options.hasOwnProperty(param) ? options[param] + '' : ''; options.hasOwnProperty(param) ? options[param] + '' : '';
} }
}), });
// added: exists, create, min, max, isFile, isDirectory, validate // added: exists, create, min, max, isFile, isDirectory, validate
validPath, error = ''; /* eslint-enable key-spacing */
options = options || {}; options = options || {};
/* jshint eqnull:true */ if (query == null) { query = 'Input path (you can "cd" and "pwd") :'; } // eslint-disable-line eqeqeq
if (query == null) { query = 'Input path (you can "cd" and "pwd") :'; }
/* jshint eqnull:false */
exports.question(query, readOptions); exports.question(query, readOptions);
return validPath; return validPath;
@ -1090,6 +1101,7 @@ function getClHandler(commandHandler, options) {
} }
exports.promptCL = function(commandHandler, options) { exports.promptCL = function(commandHandler, options) {
/* eslint-disable key-spacing */
var readOptions = margeOptions({ var readOptions = margeOptions({
// -------- default // -------- default
hideEchoBack: false, hideEchoBack: false,
@ -1101,6 +1113,7 @@ exports.promptCL = function(commandHandler, options) {
// trueValue, falseValue, keepWhitespace don't work. // trueValue, falseValue, keepWhitespace don't work.
// preCheck, limit (by clHandler) // preCheck, limit (by clHandler)
clHandler = getClHandler(commandHandler, readOptions); clHandler = getClHandler(commandHandler, readOptions);
/* eslint-enable key-spacing */
readOptions.limit = clHandler.limit; readOptions.limit = clHandler.limit;
readOptions.preCheck = clHandler.preCheck; readOptions.preCheck = clHandler.preCheck;
exports.prompt(readOptions); exports.prompt(readOptions);
@ -1108,6 +1121,7 @@ exports.promptCL = function(commandHandler, options) {
}; };
exports.promptLoop = function(inputHandler, options) { exports.promptLoop = function(inputHandler, options) {
/* eslint-disable key-spacing */
var readOptions = margeOptions({ var readOptions = margeOptions({
// -------- default // -------- default
hideEchoBack: false, hideEchoBack: false,
@ -1116,11 +1130,13 @@ exports.promptLoop = function(inputHandler, options) {
caseSensitive: false, caseSensitive: false,
history: true history: true
}, options); }, options);
/* eslint-enable key-spacing */
while (true) { if (inputHandler(exports.prompt(readOptions))) { break; } } while (true) { if (inputHandler(exports.prompt(readOptions))) { break; } }
return; return;
}; };
exports.promptCLLoop = function(commandHandler, options) { exports.promptCLLoop = function(commandHandler, options) {
/* eslint-disable key-spacing */
var readOptions = margeOptions({ var readOptions = margeOptions({
// -------- default // -------- default
hideEchoBack: false, hideEchoBack: false,
@ -1132,6 +1148,7 @@ exports.promptCLLoop = function(commandHandler, options) {
// trueValue, falseValue, keepWhitespace don't work. // trueValue, falseValue, keepWhitespace don't work.
// preCheck, limit (by clHandler) // preCheck, limit (by clHandler)
clHandler = getClHandler(commandHandler, readOptions); clHandler = getClHandler(commandHandler, readOptions);
/* eslint-enable key-spacing */
readOptions.limit = clHandler.limit; readOptions.limit = clHandler.limit;
readOptions.preCheck = clHandler.preCheck; readOptions.preCheck = clHandler.preCheck;
while (true) { while (true) {
@ -1142,6 +1159,7 @@ exports.promptCLLoop = function(commandHandler, options) {
}; };
exports.promptSimShell = function(options) { exports.promptSimShell = function(options) {
/* eslint-disable key-spacing */
return exports.prompt(margeOptions({ return exports.prompt(margeOptions({
// -------- default // -------- default
hideEchoBack: false, hideEchoBack: false,
@ -1158,15 +1176,16 @@ exports.promptSimShell = function(options) {
':$<cwdHome>$ '; ':$<cwdHome>$ ';
})() })()
})); }));
/* eslint-enable key-spacing */
}; };
function _keyInYN(query, options, limit) { function _keyInYN(query, options, limit) {
var res; var res;
/* jshint eqnull:true */ if (query == null) { query = 'Are you sure? :'; } // eslint-disable-line eqeqeq
if (query == null) { query = 'Are you sure? :'; } if ((!options || options.guide !== false) && (query += '')) {
/* jshint eqnull:false */ query = query.replace(/\s*:?\s*$/, '') + ' [y/n] :';
if ((!options || options.guide !== false) && (query += '')) }
{ query = query.replace(/\s*:?\s*$/, '') + ' [y/n] :'; } /* eslint-disable key-spacing */
res = exports.keyIn(query, margeOptions(options, { res = exports.keyIn(query, margeOptions(options, {
// -------- forced // -------- forced
hideEchoBack: false, hideEchoBack: false,
@ -1177,18 +1196,18 @@ function _keyInYN(query, options, limit) {
// mask doesn't work. // mask doesn't work.
})); }));
// added: guide // added: guide
/* eslint-enable key-spacing */
return typeof res === 'boolean' ? res : ''; return typeof res === 'boolean' ? res : '';
} }
exports.keyInYN = function(query, options) { return _keyInYN(query, options); }; exports.keyInYN = function(query, options) { return _keyInYN(query, options); };
exports.keyInYNStrict = function(query, options) exports.keyInYNStrict = function(query, options) { return _keyInYN(query, options, 'yn'); };
{ return _keyInYN(query, options, 'yn'); };
exports.keyInPause = function(query, options) { exports.keyInPause = function(query, options) {
/* jshint eqnull:true */ if (query == null) { query = 'Continue...'; } // eslint-disable-line eqeqeq
if (query == null) { query = 'Continue...'; } if ((!options || options.guide !== false) && (query += '')) {
/* jshint eqnull:false */ query = query.replace(/\s+$/, '') + ' (Hit any key)';
if ((!options || options.guide !== false) && (query += '')) }
{ query = query.replace(/\s+$/, '') + ' (Hit any key)'; } /* eslint-disable key-spacing */
exports.keyIn(query, margeOptions({ exports.keyIn(query, margeOptions({
// -------- default // -------- default
limit: null limit: null
@ -1198,10 +1217,12 @@ exports.keyInPause = function(query, options) {
mask: '' mask: ''
})); }));
// added: guide // added: guide
/* eslint-enable key-spacing */
return; return;
}; };
exports.keyInSelect = function(items, query, options) { exports.keyInSelect = function(items, query, options) {
/* eslint-disable key-spacing */
var readOptions = margeOptions({ var readOptions = margeOptions({
// -------- default // -------- default
hideEchoBack: false hideEchoBack: false
@ -1219,8 +1240,10 @@ exports.keyInSelect = function(items, query, options) {
}), }),
// added: guide, cancel // added: guide, cancel
keylist = '', key2i = {}, charCode = 49 /* '1' */, display = '\n'; keylist = '', key2i = {}, charCode = 49 /* '1' */, display = '\n';
if (!Array.isArray(items) || !items.length || items.length > 35) /* eslint-enable key-spacing */
{ throw '`items` must be Array (max length: 35).'; } if (!Array.isArray(items) || !items.length || items.length > 35) {
throw '`items` must be Array (max length: 35).';
}
items.forEach(function(item, i) { items.forEach(function(item, i) {
var key = String.fromCharCode(charCode); var key = String.fromCharCode(charCode);
@ -1232,21 +1255,18 @@ exports.keyInSelect = function(items, query, options) {
if (!options || options.cancel !== false) { if (!options || options.cancel !== false) {
keylist += '0'; keylist += '0';
key2i['0'] = -1; key2i['0'] = -1;
/* jshint eqnull:true */ display += '[0] ' +
display += '[' + '0' + '] ' + (options && options.cancel != null && typeof options.cancel !== 'boolean' ? // eslint-disable-line eqeqeq
(options && options.cancel != null && typeof options.cancel !== 'boolean' ?
(options.cancel + '').trim() : 'CANCEL') + '\n'; (options.cancel + '').trim() : 'CANCEL') + '\n';
/* jshint eqnull:false */
} }
readOptions.limit = keylist; readOptions.limit = keylist;
display += '\n'; display += '\n';
/* jshint eqnull:true */ if (query == null) { query = 'Choose one from list :'; } // eslint-disable-line eqeqeq
if (query == null) { query = 'Choose one from list :'; }
/* jshint eqnull:false */
if ((query += '')) { if ((query += '')) {
if (!options || options.guide !== false) if (!options || options.guide !== false) {
{ query = query.replace(/\s*:?\s*$/, '') + ' [$<limit>] :'; } query = query.replace(/\s*:?\s*$/, '') + ' [$<limit>] :';
}
display += query; display += query;
} }