-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.js
102 lines (89 loc) · 2.41 KB
/
cli.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
const arg = require('arg');
const readline = require('readline');
const chalk = require('chalk');
let rl;
let commands = [];
let cmdHelpText = '';
let cmdHelp = {};
let aliases = { };
function setCommandLineHelp(k, v) {
cmdHelp[k] = v;
}
function initCommandLine(cmd0, commandLineArgs) {
cmdHelpText = `Usage: ${chalk.yellow(cmd0)} [${chalk.green('options')}], where ${chalk.green('options')} can be:\n`;
for (let k in commandLineArgs) {
let opt = commandLineArgs[k];
if (typeof opt === 'string') {
if (aliases[k] === undefined) aliases[k] = []; // first one for [k]
aliases[k].push(opt);
} else {
let desc = cmdHelp[k] || '(missing help description)';
cmdHelpText += ` ${chalk.yellow(k)} (${desc})\n`;
}
}
cmdHelpText += `These options also have these short-form ${chalk.green('aliases')}:\n`;
for (let a in aliases) {
cmdHelpText += ` ${chalk.yellow(a)}: ${chalk.green(aliases[a].join(' '))}\n`;
}
return arg(commandLineArgs);
}
function onCommandLineHelp() {
console.log(cmdHelpText);
}
function onHelp() {
let cmds = [ ];
for (let cmd in commands) {
if (commands.hasOwnProperty(cmd)) {
cmds.push(cmd);
}
}
console.log(`The following commands are available:\n${cmds.join(', ')}`);
}
function onQuit() {
rl.close();
}
function init(input, output) {
rl = readline.createInterface({input, output});
addCommand(onHelp, ['help', '?']);
addCommand(onQuit, ['quit', 'exit', 'bye']);
}
function addCommand(handler, cmds) {
if (!(handler && cmds)) return;
if (!Array.isArray(cmds))
cmds = [ cmds ];
for (let cmd of cmds) {
commands[cmd.toLowerCase()] = handler;
}
}
async function processLine(line) {
let trimmed = line.trim();
if (!trimmed) return;
let tokens = trimmed.split(' ');
let cmd = tokens[0].toLowerCase();
if (commands.hasOwnProperty(cmd)) {
let handler = commands[cmd];
try {
await handler(tokens, trimmed)
} catch (err) {
console.log("Exception start:");
console.log(err.message);
console.log("Exception end.");
}
} else {
console.log(`Command '${cmd}' not recognized.`);
}
}
async function run() {
rl.prompt();
rl.on('line', async (line) => {
await processLine(line);
rl.prompt();
});
await rl.on("close", () => {
process.exit(0);
});
}
module.exports = {
setCommandLineHelp, initCommandLine, onCommandLineHelp,
init, addCommand, process, run
}