-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli-repl.ts
294 lines (255 loc) · 6.29 KB
/
cli-repl.ts
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import { Terminal } from 'xterm';
import {
runCliAndExit,
IRunCliAndExitOptions,
Cli,
ICliBranch,
ICliCommand,
CliBranch,
} from '@carnesen/cli';
import { CommandLineHistory } from './command-line-history';
import { green, yellow, splitWords, bold } from './util';
import { HistoryCommand } from './history-command';
import { autocomplete } from './autocomplete';
const INDENTATION = ' ';
export interface ICliReplOptions {
/** [[`ICliBranch`]] and/or [[`ICliCommand`]]s underneath this branch */
subcommands: (ICliBranch | ICliCommand<any, any, any>)[];
/** An XTerm.js Terminal to run the REPL in */
terminal: Terminal;
/** A short description of this branch for command-line usage */
description?: string;
/** History lines */
history?: string[];
/** Initial command line */
line?: string;
/** Whether or not to submit the initial line */
submit?: boolean;
}
type KeyEvent = { key: string; domEvent: KeyboardEvent };
const PS1 = `${green('$')} `;
export class CliRepl {
private readonly terminal: Terminal;
private runningCommand = false;
private settingCurrentLine = false;
private readonly commandLineHistory: CommandLineHistory;
private line = '';
private submit: boolean;
private index = 0;
private readonly root: ICliBranch;
public constructor({
description,
subcommands,
terminal,
history,
line,
submit,
}: ICliReplOptions) {
this.terminal = terminal;
this.commandLineHistory = new CommandLineHistory(history, line);
this.line = this.commandLineHistory.current();
this.submit = submit || false;
const builtInCommands = [HistoryCommand(this.commandLineHistory)];
this.root = CliBranch({
description,
name: '',
subcommands: [...subcommands, ...builtInCommands],
});
}
public start(): void {
this.terminal.onKey((event) => {
this.handleKeyEvent(event);
});
this.terminal.focus();
if (!this.submit) {
this.consoleLog(`Hit ${bold('"Enter"')} to get started.`);
}
this.prompt();
if (this.submit) {
this.handleEnterKeyEvent();
}
}
private prompt() {
this.terminal.write(`\r\n${PS1}${this.line}`);
}
private handleKeyEvent({ key, domEvent }: KeyEvent): void {
if (this.settingCurrentLine) {
return;
}
if (this.runningCommand) {
return;
}
const printable =
!domEvent.altKey && !domEvent.ctrlKey && !domEvent.metaKey;
domEvent.preventDefault();
switch (domEvent.keyCode) {
case 8: {
// delete
if (this.index === 0) {
break;
}
const line =
this.line.substring(0, this.index - 1) +
this.line.substring(this.index, this.line.length);
this.setLine(line, this.index - 1);
break;
}
case 9: {
// tab
this.autocomplete();
break;
}
case 13: {
// enter
this.handleEnterKeyEvent();
break;
}
case 37: {
// left arrow
if (this.index === 0) {
break;
}
this.terminal.write(key);
this.index -= 1;
break;
}
case 38: {
// up arrow
this.setLine(this.commandLineHistory.previous(this.line));
break;
}
case 39: {
// right arrow
if (this.index === this.line.length) {
break;
}
this.terminal.write(key);
this.index += 1;
break;
}
case 40: {
// down arrow
this.setLine(this.commandLineHistory.next(this.line));
break;
}
default: {
if (printable) {
this.addToLine(key);
}
}
}
}
private consoleLog(arg: any) {
if (typeof arg === 'string') {
for (const ln of arg.split('\n')) {
this.terminal.writeln(ln);
}
} else if (typeof arg === 'number') {
this.terminal.writeln(yellow(String(arg)));
} else if (typeof arg === 'object' && typeof arg.stack === 'string') {
// Error object
for (const line of arg.stack.split('\n')) {
this.terminal.writeln(line);
}
} else {
this.terminal.writeln(String(arg));
}
}
private consoleError(arg: any) {
this.consoleLog(arg);
}
private runCurrentLine() {
const options: IRunCliAndExitOptions = {
args: splitWords(this.line),
consoleError: (...args: any[]) => {
this.consoleError(args[0]);
},
consoleLog: (...args: any[]) => {
this.consoleLog(args[0]);
},
processExit() {},
columns: this.terminal.cols,
};
this.runningCommand = true;
this.terminal.write('\r\n');
runCliAndExit(Cli(this.root), options)
.catch((err) => {
console.log(err); // eslint-disable-line no-console
})
.then(() => {
this.line = '';
this.index = 0;
this.runningCommand = false;
this.prompt();
});
}
private setLine(line: string, index?: number) {
if (line === this.line) {
return;
}
this.settingCurrentLine = true;
const changeInLength = line.length - this.line.length;
let sequence = '';
sequence += '\r';
sequence += PS1;
sequence += line;
if (changeInLength < 0) {
sequence += ' '.repeat(-1 * changeInLength);
sequence += '\b'.repeat(-1 * changeInLength);
}
if (typeof index === 'number') {
sequence += '\b'.repeat(line.length - index);
}
this.terminal.write(sequence, () => {
this.line = line;
this.index = typeof index === 'number' ? index : line.length;
this.settingCurrentLine = false;
});
}
private handleEnterKeyEvent() {
this.commandLineHistory.submit(this.line);
this.runCurrentLine();
}
private addToLine(str: string) {
const line =
this.line.substring(0, this.index) +
str +
this.line.substring(this.index);
this.setLine(line, this.index + str.length);
}
private autocomplete(): void {
const lineBeforeCursor = this.line.substring(0, this.index);
const wordsBeforeCursor = splitWords(lineBeforeCursor);
let args: string[];
let search = '';
if (lineBeforeCursor.endsWith(' ')) {
search = '';
args = wordsBeforeCursor;
} else {
[search = ''] = wordsBeforeCursor.slice(-1);
args = wordsBeforeCursor.slice(0, -1);
}
const completions = autocomplete(this.root, args, search);
switch (completions.length) {
case 0: {
return;
}
case 1: {
this.addToLine(completions[0]);
break;
}
default: {
// Write out the completions
this.consoleLog('');
for (const completion of completions) {
this.consoleLog(`${INDENTATION}${search}${completion}`);
}
// Re-write line
const countAfterCursor = this.line.length - this.index;
this.terminal.write(
`${PS1}${this.line}${'\b'.repeat(countAfterCursor)}`,
);
}
}
}
}