-
-
Notifications
You must be signed in to change notification settings - Fork 122
/
repl.mts
451 lines (389 loc) · 16.4 KB
/
repl.mts
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
import assert from 'node:assert';
import readline from 'node:readline/promises';
import { formatWithOptions } from 'node:util';
import * as vscode from 'vscode';
import { clearScreen, crlf, green, red, yellow } from './ansiUtils.mjs';
import { Application, Command, defArg } from './args.mjs';
import { cmdLs } from './cmdLs.mjs';
import { traceWord } from './cmdTrace.mjs';
import { consoleDebug } from './consoleDebug.mjs';
import { emitterToReadStream, emitterToWriteStream } from './emitterToWriteStream.mjs';
import type { DirEntry } from './fsUtils.mjs';
import { currentDirectory, globSearch, readDir, resolvePath, toRelativeWorkspacePath } from './fsUtils.mjs';
import { globsToGlob } from './globUtils.mjs';
import { commandLineBuilder, parseCommandLineIntoArgs } from './parseCommandLine.js';
export function createTerminal() {
const pty = new Repl();
const terminal = vscode.window.createTerminal({ name: 'Spell Checker REPL', pty });
terminal.show();
}
class Repl implements vscode.Disposable, vscode.Pseudoterminal {
readonly #emitterInput = new vscode.EventEmitter<string>();
readonly #emitterOutput = new vscode.EventEmitter<string>();
readonly #emitterOnDidClose = new vscode.EventEmitter<void>();
readonly onDidWrite = this.#emitterOutput.event;
readonly onDidClose = this.#emitterOnDidClose.event;
readonly handleInput = (data: string) => this.#emitterInput.fire(data);
readonly #writeStream = emitterToWriteStream(this.#emitterOutput);
readonly #readStream = emitterToReadStream(this.#emitterInput);
readonly #output = (value: string) => this.#emitterOutput.fire(value);
readonly #controller = new AbortController();
readonly #abortable = { signal: this.#controller.signal };
#cwd = currentDirectory();
#cancelationTokenSource: vscode.CancellationTokenSource | undefined;
#rl: readline.Interface | undefined;
#closed = false;
#dimensions: vscode.TerminalDimensions | undefined;
#application: Application | undefined;
constructor() {}
open(dimensions: vscode.TerminalDimensions | undefined) {
consoleDebug('Repl.open');
assert(!this.#rl, 'Repl already open');
assert(!this.#closed, 'Repl already closed');
if (dimensions) {
this.#dimensions = dimensions;
this.#writeStream.dimensions = dimensions;
}
this.#rl = readline.createInterface({
input: this.#readStream,
output: this.#writeStream,
completer: this.completer,
terminal: true,
});
const rl = this.#rl;
rl.on('SIGTSTP', () => undefined);
rl.on('SIGINT', this.#cancelAction);
rl.on('close', () => (consoleDebug('rl close'), this.close()));
rl.on('line', this.#processLine);
this.#dimensions = dimensions;
if (dimensions) {
this.log('CSpell REPL');
this.log('Type "help" or "?" for help.');
this.#prompt();
}
}
setDimensions(dimensions: vscode.TerminalDimensions) {
this.#dimensions = dimensions;
this.#writeStream.dimensions = dimensions;
consoleDebug('Repl.setDimensions %o', dimensions);
this.#updatePrompt();
}
dispose = () => {
consoleDebug('Repl.dispose');
this.close();
};
#processLine = (line: string) => {
line = line.trim();
consoleDebug('Repl.processLine %o', { line, args: parseCommandLineIntoArgs(line) });
const parseAsync = async () => {
if (!line) return;
if (line === '?') {
this.showHelp();
return;
}
const argv = parseCommandLineIntoArgs(line);
return this.#getApplication().exec(argv);
};
this.#prompt(parseAsync());
};
#getApplication(): Application {
if (this.#application) return this.#application;
const app = new Application('CSpell REPL');
const cmdCheck = new Command(
'check',
'Spell check the files matching the globs.',
{ ...defArg('globs', 'string[]', 'File glob patterns.') },
{},
(args) => this.#cmdCheck(args.args.globs),
);
const cmdEcho = new Command(
'echo',
'Echo the values.',
{ ...defArg('values', 'string[]', 'Echo the values to the console.') },
{},
(args) => this.#cmdEcho(args.args.values),
);
const cmdTrace = new Command(
'trace',
'Trace which dictionaries contain the word.',
{ ...defArg('word', 'string', 'The word to trace.', true) },
{},
(args) => this.#cmdTrace(args.args),
);
const cmdPwd = new Command('pwd', 'Print the current working directory.', {}, {}, () => this.#cmdPwd());
const cmdCd = new Command(
'cd',
'Change the current working directory.',
{ ...defArg('path', 'string', 'The path to change to.') },
{},
(args) => this.#cmdCd(args.args.path),
);
const cmdLs = new Command(
'ls',
'List the directory contents.',
{ ...defArg('paths', 'string[]', 'The paths to list.') },
{},
(args) => this.#cmdLs(args.args),
);
const cmdEnv = new Command(
'env',
'Show environment variables.',
{ ...defArg('filter', 'string[]', 'Optional filter.') },
{},
(args) => this.#cmdEnv(args.args.filter),
);
const cmdExit = new Command('exit', 'Exit the REPL.', {}, {}, () => {
this.log('Exiting...');
this.close();
});
const cmdHelp = new Command(
'help',
'Show help.',
{
command: { type: 'string', description: 'Show Help', required: false },
},
{},
(args) => this.showHelp(args.args.command),
);
const cmdCls = new Command('cls', 'Clear the screen.', {}, {}, () => this.#output(clearScreen()));
const cmdInfo = new Command('info', 'Show information about the REPL.', {}, {}, () => {
this.log('CSpell REPL');
this.log('Type "help" or "?" for help.');
this.log('Working Directory: %s', green(this.#cwd.toString(true)));
this.log('Dimensions: %o', this.#dimensions);
});
const commands = [cmdCheck, cmdEcho, cmdTrace, cmdPwd, cmdCd, cmdLs, cmdEnv, cmdExit, cmdHelp, cmdCls, cmdInfo];
app.addCommands(commands);
this.#application = app;
return app;
}
showHelp(command?: string) {
this.log(this.#getApplication().getHelp(command));
}
#prompt(waitFor?: Promise<unknown>) {
const p = async () => {
try {
await waitFor;
if (waitFor) {
// clean up the action.
this.#cancelationTokenSource?.dispose();
this.#cancelationTokenSource = undefined;
} else {
if (this.#cancelationTokenSource) {
// It is busy, do not display the prompt.
// It is possible to get here if the dimensions of the window change
// while in the middle of an action.
return;
}
}
} catch (e) {
if (e instanceof Error) {
this.error(e.message);
}
// empty
}
this.#updatePrompt();
this.#rl?.prompt();
if (this.#rl) {
const { cursor, line, terminal } = this.#rl;
consoleDebug('cursor pos: %o', { cursorPos: this.#rl.getCursorPos(), dim: this.#dimensions, cursor, line, terminal });
}
};
p();
}
#updatePrompt() {
this.#rl?.setPrompt(`cspell ${green(toRelativeWorkspacePath(vscode.Uri.joinPath(this.#cwd, '/')) || '')} > `);
}
async #cmdCheck(globs: string[] | undefined) {
consoleDebug('Repl.cmdCheck');
let pattern = globsToGlob(globs);
if (!pattern) {
pattern = await this.#rl?.question('File glob pattern: ', this.#abortable);
}
if (!pattern) return;
this.log('Checking...');
const cfgSearchExclude = vscode.workspace.getConfiguration('search.exclude') as { [key: string]: boolean };
const searchExclude = Object.keys(cfgSearchExclude).filter((k) => cfgSearchExclude[k] === true);
const excludePattern = globsToGlob(searchExclude);
const files = await globSearch(pattern, currentDirectory(), excludePattern, undefined, this.#getCancelationTokenForAction());
files.forEach((f) => this.#output(`File: ${colorText(vscode.workspace.asRelativePath(f, true))}\r\n`));
}
async #cmdEcho(globs: string[] | undefined) {
consoleDebug('Repl.cmdEcho');
this.log((globs || []).join(' '));
}
getCommandNames() {
return this.#getApplication().getCommandNames().sort();
}
completer = async (line: string): Promise<[string[], string]> => {
const commands = this.getCommandNames();
if (!line.trim()) return [commands, ''];
const cmdLine = commandLineBuilder(line);
const args = cmdLine.args;
if (args.length === 1 && line === args[0]) {
return [this.#completeWithOptions(line, commands).map((line) => line + ' '), line];
}
const command = args[0];
const argIndex = cmdLine.hasTrailingSeparator() ? 0 : args.length - 1;
const current = argIndex ? args[argIndex] : '';
const results = await this.#cmdCompletion(command, current, args);
const completions = results.map((c) => {
const cmd = cmdLine.clone();
if (argIndex) {
cmd.setArg(argIndex, c);
} else {
cmd.pushArg(c);
}
return cmd.line;
});
return [completions.filter((c) => c.startsWith(line)), line];
};
#cmdCompletion = async (command: string, current: string, args: string[]) => {
console.error('Repl.cmdCompletion %o', { command, current });
switch (command) {
case 'check':
return this.#cmdCheckCompletion(current);
case 'cd':
return this.#cmdCdCompletion(current, args);
case 'ls':
return this.#completeWithPath(current, false);
case 'help':
return this.#completeWithOptions(current, this.getCommandNames());
}
return [];
};
#cmdCheckCompletion = async (current: string) => {
return this.#completeWithPath(current, false);
};
#cmdCdCompletion = async (current: string, args: string[]) => {
if (args.length > 2 || (args.length === 2 && args[1] !== current)) return [];
return this.#completeWithPath(current, true);
};
#completeWithPath = async (current: string, directoriesOnly: boolean) => {
try {
const files = await this.readDirEntryNames(current, directoriesOnly ? vscode.FileType.Directory : undefined);
return this.#completeWithOptions(
current,
files.map((f) => (f.startsWith('-') ? `./${f}` : f)),
);
} catch {
return [];
}
};
#completeWithOptions = (current: string, options: string[]): string[] => {
// console.error('Repl.completeWithOptions %o', { current, options });
const matchingCommands = options.filter((c) => c.startsWith(current));
const prefix = findLongestPrefix(matchingCommands);
return prefix && prefix !== current ? [prefix] : matchingCommands;
};
#cmdPwd() {
consoleDebug('Repl.cmdPwd');
this.log(this.#cwd?.toString(false) || 'No Working Directory');
}
#cmdEnv(filter?: string[] | undefined) {
consoleDebug('Repl.cmdEnv');
this.log('Environment:');
const entries = Object.entries(process.env)
.filter(([key]) => !filter || filter.find((f) => key.toLowerCase().includes(f)))
.sort((a, b) => a[0].localeCompare(b[0]));
for (const [key, value] of entries) {
this.log(`${green(key)}${yellow('=')}${value}`);
}
}
async #cmdTrace(args: { word?: string | undefined }) {
consoleDebug('Repl.cmdTrace %o', args);
const { word } = args;
if (!word) {
this.log('No word specified.');
return;
}
const result = await traceWord(word, vscode.window.activeTextEditor?.document.uri || this.#cwd, this.#dimensions?.columns || 80);
this.log('%s', result);
}
async #cmdLs(args: { paths?: string[] | undefined }) {
consoleDebug('Repl.cmdLs %o', args);
await cmdLs(args.paths, { log: this.log, cwd: this.#cwd, cancelationToken: this.#getCancelationTokenForAction() });
}
async readDir(relUri?: string | vscode.Uri | undefined): Promise<DirEntry[]> {
return readDir(relUri, this.#cwd);
}
async readDirEntryNames(relativePartialPath: string, filterType?: vscode.FileType): Promise<string[]> {
const relPath = relativePartialPath.split('/').slice(0, -1).join('/');
const filterFn = filterType ? ([, type]: Readonly<[string, vscode.FileType]>) => type & filterType : () => true;
const defaultDir: DirEntry[] = relPath ? [] : [['..', vscode.FileType.Directory]];
const relPrefix = relPath ? relPath + '/' : '';
const dirInfo = [...defaultDir, ...(await this.readDir(relPath)).map(([name, type]) => [relPrefix + name, type] as DirEntry)]
.filter(filterFn)
.map(([name, type]) => name + (type & vscode.FileType.Directory ? '/' : ''));
return dirInfo;
}
async #cmdCd(path?: string) {
if (!path) {
return this.#cmdPwd();
}
try {
const dirUri = resolvePath(path, this.#cwd);
const s = await vscode.workspace.fs.stat(dirUri);
if (s.type & vscode.FileType.Directory) {
this.#cwd = dirUri;
} else {
throw vscode.FileSystemError.FileNotADirectory(dirUri);
}
} catch (e) {
if (e instanceof vscode.FileSystemError) {
this.log(`"${path}" is not a valid directory.`);
return;
}
this.log('Error: %o', e);
}
}
close = () => {
consoleDebug('Repl.close');
if (this.#closed) return;
this.#closed = true;
this.#cancelationTokenSource?.cancel();
this.#controller.abort();
this.#rl?.close();
this.#readStream.destroy();
this.#writeStream.destroy();
this.#emitterOnDidClose.fire();
this.#cancelationTokenSource?.dispose();
this.#cancelationTokenSource = undefined;
};
log: typeof console.log = (...args) => this.#output(crlf(formatWithOptions({ colors: true }, ...args) + '\n'));
error: typeof console.error = (...args) => this.#output(red('Error: ') + crlf(formatWithOptions({ colors: true }, ...args) + '\n'));
#cancelAction = () => this.#cancelationTokenSource?.cancel();
#createCancelationTokenForAction(): vscode.CancellationToken {
return this.#createCancelationTokenSourceForAction().token;
}
#getCancelationTokenForAction(): vscode.CancellationToken {
return this.#cancelationTokenSource?.token || this.#createCancelationTokenForAction();
}
#createCancelationTokenSourceForAction(): vscode.CancellationTokenSource {
this.#cancelationTokenSource?.dispose();
const t = abortControllerToCancelationTokenSource(this.#controller);
this.#cancelationTokenSource = t;
return t;
}
}
function colorText(text: string): string {
return green(text);
}
function abortControllerToCancelationTokenSource(ac: AbortController): vscode.CancellationTokenSource {
const t = new vscode.CancellationTokenSource();
ac.signal.onabort = () => t.cancel();
return t;
}
function findLongestPrefix(values: string[]): string {
if (!values.length) return '';
let val = values[0];
for (const v of values) {
let i = 0;
for (; i < val.length && i < v.length; ++i) {
if (val[i] !== v[i]) break;
}
val = val.slice(0, i);
if (!val) return val;
}
return val;
}