-
-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathlips.js
executable file
·906 lines (847 loc) · 29.1 KB
/
lips.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
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
#!/usr/bin/env node
import lily from '@jcubic/lily';
const boolean = [
'd', 'dynamic', 'q', 'quiet', 'V', 'version', 'trace', 't', 'c', 'compile'
];
const options = lily(process.argv.slice(2), { boolean });
const quiet = options.q || options.quiet;
import {
exec,
compile,
parse,
Parser,
Formatter,
serialize,
unserialize,
serialize_bin,
unserialize_bin,
balanced_parenthesis,
tokenize,
_is_directive,
Interpreter,
LSymbol,
Macro,
LString,
evaluate,
nil,
Pair,
env,
InputPort,
OutputPort
} from '../src/lips.js';
import { version, date, banner } from '../dist/lips.esm.js';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { format } from 'util';
import readline from 'readline';
import highlight from 'prism-cli';
import Prism from 'prismjs';
import 'prismjs/components/prism-scheme.min.js';
import { satisfies } from 'compare-versions';
import '../lib/js/prism.js';
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const kDebounceHistoryMS = 15;
const supports_paste_brackets = satisfies(process.version, '>=v20.6.0');
// -----------------------------------------------------------------------------
process.on('uncaughtException', function (err) {
log_error(err.message);
log_error(err.stack);
});
// -----------------------------------------------------------------------------
function log_error(message) {
const date = (new Date()).toISOString();
message = message.split('\n').map(line => {
return `${date}: ${line}`;
}).join('\n');
fs.appendFileSync(home_file('lips.error.log'), message + '\n');
}
function home_file(filename) {
return path.join(os.homedir(), filename);
}
// -----------------------------------------------------------------------------
function debug(message) {
console.log(message);
}
// -----------------------------------------------------------------------------
async function run(code, interpreter, use_dynamic = false, env = null, stack = false, log_unterminated = true) {
try {
return await interpreter.exec(code, { use_dynamic, env });
} catch(e) {
if (e instanceof Parser.Unterminated && !log_unterminated) {
return;
}
print_error(e, stack);
}
}
// -----------------------------------------------------------------------------
function print_error(e, stack) {
if (!e) {
console.log('Error is null');
return;
}
log_error(e.message);
if (e.__code__) {
strace = e.__code__.map((line, i) => {
const prefix = `[${i+1}]: `;
const formatter = new Formatter(line);
const output = formatter.break().format({
offset: prefix.length
});
return prefix + output;
}).join('\n');
}
if (stack) {
console.error(e.stack);
console.error(strace);
process.exit(1);
} else {
console.error(e.message);
console.error('Call (stack-trace) to see the stack');
console.error('Thrown exception is in global exception variable, use ' +
'(display exception.stack) to display JS stack trace');
}
global.exception = e;
}
// -----------------------------------------------------------------------------
function print(result) {
if (result && result.length) {
const last = result.pop();
if (last !== undefined) {
try {
const ret = env.get('repr')(last, true);
process.stdout.write('\x1b[K' + ret.toString());
return true;
} catch(e) {
print_error(e, options.t || options.trace);
}
}
}
}
// -----------------------------------------------------------------------------
function bootstrap(interpreter) {
const bootstrap = options.b || options.bootstrap;
if (bootstrap === 'none') {
return Promise.resolve();
}
const file = bootstrap ? bootstrap : './dist/std.xcb';
function read(name) {
var path;
try {
path = require.resolve(`./${name}`);
} catch (e) {
try {
path = require.resolve(`../${name}`);
} catch (e) {
path = require.resolve(`@jcubic/lips/../${name}`);
}
}
return readCode(path);
}
const code = read(file);
return run(code, interpreter, false, env.__parent__, true);
}
// -----------------------------------------------------------------------------
function readCode(filename) {
if (compiled_binary(filename)) {
return unserialize_bin(readBinary(filename));
} else {
const code = readFile(filename);
if (compiled(filename)) {
return unserialize(code);
}
return code;
}
}
// -----------------------------------------------------------------------------
function compiled(name) {
return name.match(/\.xcm$/);
}
// -----------------------------------------------------------------------------
function compiled_binary(name) {
return name.match(/\.xcb$/);
}
// -----------------------------------------------------------------------------
function indent(code, indent, offset) {
var formatter = new Formatter(code);
return formatter.indent({
indent,
offset
});
}
// -----------------------------------------------------------------------------
function doc(fn, doc) {
fn.__doc__ = doc.split('\n').map(function(line) {
return line.trim();
}).join('\n');
return fn;
}
// -----------------------------------------------------------------------------
function scheme(str) {
return highlight(str, 'scheme', {
grammar: Prism.languages.scheme,
newlines: true
});
}
// -----------------------------------------------------------------------------
function log(message) {
if (typeof message !== 'string') {
message = message.toString();
}
fs.appendFile('out.log', message + '\n', (err) => { });
}
// -----------------------------------------------------------------------------
let strace;
let rl;
let buffer;
var newline;
const moduleURL = new URL(import.meta.url);
const __dirname = path.dirname(moduleURL.pathname);
const __filename = path.basename(moduleURL.pathname);
const command_line = [];
let last_line = '';
const interp = Interpreter('repl', {
stdin: InputPort(function() {
return new Promise(function(resolve) {
rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question(last_line, function(data) {
resolve(data);
rl.close();
});
});
}),
// -------------------------------------------------------------------------
stdout: OutputPort(function(x) {
if (typeof x !== 'string') {
x = this.get('repr')(x);
}
newline = !x.match(/\n$/);
last_line = x.split('\n').pop();
process.stdout.write(x);
}),
// -------------------------------------------------------------------------
__dirname: __dirname,
__filename: __filename,
command_line,
// -------------------------------------------------------------------------
'stack-trace': doc(function() {
if (strace) {
console.log(strace);
}
}, `(stack-trace)
Function display stack trace of last error`),
// -------------------------------------------------------------------------
exit: doc(function(code) {
process.exit(code);
}, `(exit)
(exit error-code)
Function exits LIPS script or the REPL.`),
// -------------------------------------------------------------------------
pprint: doc(function(arg) {
if (arg instanceof Pair) {
arg = new Formatter(arg.toString(true)).break().format();
this.get('display').call(this, scheme(arg));
} else {
this.get('write').call(this, scheme(arg));
}
this.get('newline').call(this);
}, env.get('pprint').__doc__),
// -------------------------------------------------------------------------
help: doc(new Macro('help', function(code, { error }) {
var new_code = new Pair(new LSymbol('__help'), code);
var doc = evaluate(new_code, { env: this, error });
if (doc) {
console.log(doc.toString());
}
}), env.get('help').__doc__),
// -------------------------------------------------------------------------
'__help': env.get('help')
});
function readBinary(filename) {
return fs.readFileSync(filename);
}
// -----------------------------------------------------------------------------
function readFile(filename) {
const buff = readBinary(filename);
return buff.toString().replace(/^(#!.*)([\s\n])/, function(_, shebang, delim) {
if (_is_directive(shebang)) {
return shebang + delim;
}
return '';
});
}
// -----------------------------------------------------------------------------
function get_command_line_args() {
const filename = options._[0];
const index = process.argv.findIndex((item) => item === filename);
return process.argv.slice(index);
}
// -----------------------------------------------------------------------------
if (options.version || options.V) {
// SRFI 176
global.output = Pair.fromArray([
["command", "lips"],
["website", "https://lips.js.org"],
['languages', 'scheme', 'r5rs', 'r7rs'].map(LSymbol),
['encodings', 'utf-8'].map(LSymbol),
["scheme.srfi", 0, 1, 2, 4, 6, 8, 10, 22, 23, 26, 28, 46, 69, 98, 111, 139, 156, 176, 193, 210, 236],
["release", version],
["os.uname", os.platform(), os.release()],
["os.env.LANG", process.env.LANG],
["os.env.TERM", process.env.TERM],
["build.date", date.match(/^\{\{|\}\}$/) ? date : new Date(date).toISOString()]
].map(([key, ...values]) => {
return [LSymbol(key), ...values];
}));
bootstrap(interp).then(function() {
return run('(for-each (lambda (x) (write x) (newline)) output)', interp, options.d || options.dynamic);
});
} else if (options.e || options.eval) {
// from 1.0 documentation should use -e but it's not breaking change
bootstrap(interp).then(function() {
const code = options.e || options.eval;
const dynamic = options.d || options.dynamic;
return run(code, interp, dynamic, null, true).then(print);
});
} else if ((options.c || options.compile) && options._.length === 1) {
try {
const filename = options._[0];
if (!quiet) {
console.log('Experimental compiler');
console.log(`Compiling ${filename} ...`);
}
const ext = '.xcb';
const compiled_name = filename.replace(/\.[^.]+$/, '') + ext;
var code = readFile(filename);
const cwd = process.cwd();
bootstrap(interp).then(function() {
return compile(code, interp.__env__).then(code => {
if (!quiet) {
console.log(`Writing ${compiled_name} ...`);
}
try {
const encoded = serialize_bin(code);
fs.writeFile(compiled_name, encoded, function(err) {
if (err) {
console.error(err);
} else if (!quiet) {
console.log('DONE');
}
});
} catch (e) {
console.error(e);
}
})
}).catch(e => {
print_error(e, true);
});
} catch(e) {
console.log(e);
}
} else if (options._.length >= 1) {
// hack for node-gtk
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.on('exit', () => {
if (rl._flushing) {
rl.pause();
return rl.once('flushHistory', () => {
process.exit();
});
}
process.exit();
});
const filename = options._[0];
command_line.push(...get_command_line_args());
try {
const code = readCode(filename);
bootstrap(interp).then(() => {
const dynamic = options.d || options.dynamic;
return run(code, interp, dynamic, null, options.t || options.trace);
});
} catch (err) {
log_error(err.message || err);
console.error(err);
} finally {
rl.close();
}
} else if (options.h || options.help) {
var name = process.argv[1];
var intro = banner.replace(/(Jankiewicz\n)[\s\S]+$/, '$1');
console.log(format('%s\nusage:\n %s -q | -c | -h | -t | -b <file> | -d | -e <code> | <filename>\n' +
'\n [-h --help]\t\tthis help message\n [-e --eval]\t\texecute code\n [-V --v' +
'ersion]\tdisplay version information according to srfi-176\n [-c --compile]\t' +
'parse and compile the file into binary file format\n [-b --boostrap]\tpoint t' +
'o a file that should be used for boostraping standard library,\n\t\t\tdefault ' +
'is ./dist/std.xcb. use none to disable boostraping\n [-q --quiet]\t\tdon\'t d' +
'isplay banner in REPL\n [-d --dynamic]\trun interpreter with dynamic scope\n ' +
' [-t --trace]\t\tprint JavaScript and scheme stack traces when extensions is th' +
'rown\n\nif called without arguments it will run the REPL and if called with on' +
'e argument\nit will treat it as filename and execute it.',
intro, path.basename(name)));
} else {
const dynamic = options.d || options.dynamic;
const entry = ' ' + (dynamic ? 'dynamic' : 'lexical') + ' scope $1';
if (process.stdin.isTTY && !quiet) {
console.log(banner.replace(/(\n\nLIPS.+)/m, entry));
}
var prompt = 'lips> ';
var continue_prompt = '... ';
var terminal = !!process.stdin.isTTY && !(process.env.EMACS || process.env.INSIDE_EMACS);
buffer = make_buffer(process.stdout);
rl = readline.createInterface({
input: process.stdin,
output: buffer,
prompt: prompt,
terminal
});
rl.on('close', () => {
setTimeout(() => {
rl.setPrompt('');
buffer.flush('\n');
}, 10);
});
const historySize = Number(env.LIPS_REPL_HISTORY_SIZE);
if (!Number.isNaN(historySize) && historySize > 0) {
rl.historySize = historySize;
} else {
rl.historySize = 1000;
}
setupHistory(rl, terminal ? env.LIPS_REPL_HISTORY : '', run_repl);
}
function is_open(token) {
return ['(', '['].includes(token);
}
function is_close(token) {
return [')', ']'].includes(token);
}
function debug_log(filename) {
return (message) => {
const payload = message.replace(/\n/g, '\\n') + '\n';
fs.appendFile(filename, payload, function (err) {
if (err) throw err;
});
};
}
// buffer Proxy to prevent flicker when Node writes to stdout
function make_buffer(stream) {
const DEBUG = false;
const buffer = [];
const fname = home_file('lips__debug.log');
if (DEBUG) {
fs.truncate(fname, 0, () => {});
}
const log = DEBUG ? debug_log(fname) : () => {};
function flush(data, ...args) {
if (buffer.length) {
const payload = buffer.join('') + data;
buffer.length = 0;
log(`flush ::: ${payload}`);
stream.write(payload, ...args);
} else {
log('write :::');
stream.write(data, ...args);
}
}
return new Proxy(stream, {
get(target, prop) {
if (prop === 'flush') {
return flush;
}
if (prop === 'write') {
return function(data, ...args) {
log(data);
if (data.match(/\x1b\[(?:1G|0J)|(^(?:lips>|\.\.\.) )/)) {
buffer.push(data);
log('buffer :::');
} else {
flush(data, ...args);
}
}
}
return target[prop];
}
});
}
// find matching open parentheses. The last token is always
// a closing parenthesis
function matched_token(code) {
try {
let count = 0;
// true to tokenize return tokens with meta data
return tokenize(code, true).reverse().find(token => {
if (is_open(token.token)) {
count--;
} else if (is_close(token.token)) {
count++;
}
return is_open(token.token) && count === 0;
});
} catch(e) {
if (!(e instanceof Parser.Unterminated)) {
throw e;
}
}
}
// highlight the open parentheses based on token metadata
function mark_paren(code, token) {
const re = /(\x1b\[[0-9;]*m)/;
let str_len = 0, found;
return code.split(re).reduce((acc, str) => {
let result
if (str.match(re)) {
result = str;
} else if (found) {
result = str;
} else if (str_len + str.length <= token.offset) {
result = str;
str_len += str.length;
} else {
const pos = token.offset - str_len;
const before = str.substring(0, pos);
const after = str.substring(pos + 1);
result = `${before}\x1b[7m(\x1b[m${after}`;
found = true;
}
return acc + result;
}, '');
}
// function accept ANSI (syntax highlighted code) and
// return ANSI escapes to overwrite the code
// this is needed to make sure that syntax highlighting
// is always correct
function ansi_rewrite_above(ansi_code) {
const lines = ansi_code.split('\n');
const stdout = lines.map((line, i) => {
const prefix = i === 0 ? prompt : continue_prompt;
return prefix + line;
}).join('\x1b[E') + '\x1b[E';
const len = lines.length;
// overwrite all lines to get rid of any artifacts left my stdin
// mostly because of parenthesis matching
return `\x1b[${len}F${stdout}`;
}
function run_repl(err, rl) {
const dynamic = options.d || options.dynamic;
let cmd = '';
let multiline = false;
let resolve;
const brackets_re = /\x1b\[(200|201)~/g;
// we use promise loop to fix issue when copy paste list of S-Expression
let prev_eval = Promise.resolve();
if (process.stdin.isTTY) {
rl.prompt();
}
let prev_line;
const is_emacs = process.env.INSIDE_EMACS;
function is_brackets_mode() {
return !!cmd.match(brackets_re);
}
function continue_multiline(code) {
multiline = true;
// we don't do indentation for paste bracket mode
// indentation will also not work for old Node.js
// because it's too problematice to make it right
if ((is_brackets_mode() || !supports_paste_brackets)) {
rl.prompt();
if (is_emacs) {
rl.setPrompt('');
} else {
rl.setPrompt(continue_prompt);
}
if (terminal) {
rl.write(' '.repeat(prompt.length - continue_prompt.length));
}
} else {
let ind;
try {
ind = indent(code, 2, prompt.length - continue_prompt.length);
} catch (e) {
ind = 0;
}
const spaces = ' '.repeat(ind);
if (is_emacs) {
rl.setPrompt('');
rl.prompt();
} else {
rl.setPrompt(continue_prompt);
rl.prompt();
rl.write(spaces);
}
}
}
function char_before_cursor() {
return rl.line[rl.cursor - 1];
}
function format_input_code(code) {
if (code) {
// we remove trailing newline from code
code = code.substring(0, code.length - 1);
return scheme(code);
}
}
let prev_token;
rl._writeToOutput = function _writeToOutput(string) {
function should_update() {
return (token || prev_token) && code_above && !string.match(/^[\n\r]+$/);
}
let token, code_above, code;
try {
const prefix = multiline ? continue_prompt : prompt;
const current_line = prefix + rl.line;
code = scheme(string);
const bracket_mode = cmd.match(brackets_re);
const full_copy_paste = bracket_mode?.length == 2;
if ((!bracket_mode || full_copy_paste) && !is_emacs) {
// clean bracket mode markers
const clean_cmd = cmd.replace(brackets_re, '');
code_above = format_input_code(clean_cmd);
if (char_before_cursor() === ')') {
const substring = rl.line.substring(0, rl.cursor);
const input = prefix + substring;
token = matched_token(input);
if (token) {
code = mark_paren(code, token);
} else if (clean_cmd) {
const input = clean_cmd + substring;
// we match paren above the current line
// but we need whole code with rl.line
// so we need to ignore rl.line
token = matched_token(input);
if (token) {
// code_above don't include the current line that
// is added after user press enter
code_above = mark_paren(code_above, token);
}
}
}
if (should_update()) {
// overwrite lines above the cursor this is side effect
process.stdout.write('\x1b7' + ansi_rewrite_above(code_above) + '\x1b8');
}
prev_token = token;
}
// this always need to be executed inside rl._writeToOutput
// even if nothing changes, this make sure that the input
// stay intact while editing the command line
rl.output.write(code);
} catch(e) {
console.error(e);
}
};
process.stdin.on('keypress', (c, k) => {
setTimeout(function() {
// we force triggering rl._writeToOutput function
// so we have the change to syntax highlight the command line
// this needs to happen on next tick so the string have time
// to updated with a given key
rl._refreshLine();
}, 0);
});
bootstrap(interp).then(function() {
if (supports_paste_brackets) {
// this make sure that the paste brackets ANSI escape
// is added to cmd so they can be processed in 'line' event
process.stdin.on('keypress', (c, k) => {
if (k?.name?.match(/^paste-/)) {
cmd += k.sequence;
}
});
// enable paste bracket mode by the terminal
process.stdout.write('\x1b[?2004h');
}
rl.on('line', function(line) {
try {
cmd += line;
const code = cmd.replace(brackets_re, '');
if (cmd.match(/\x1b\[201~$/)) {
cmd = code;
}
if (terminal) {
const output = ansi_rewrite_above(scheme(code));
process.stdout.write(output);
}
cmd += '\n';
if (balanced_parenthesis(code)) {
// we need to clear the prompt because resume
// is adding the prompt that was present when pause was called
// https://github.com/nodejs/node/issues/11699
rl.setPrompt('');
rl.pause();
prev_eval = prev_eval.then(function() {
const result = run(code, interp, dynamic, null, options.t || options.trace, false);
cmd = '';
return result;
}).then(function(result) {
if (process.stdin.isTTY) {
if (print(result) || newline) {
// readline doesn't work with not ended lines
// it ignore those, so we end them ourselves
process.stdout.write('\n');
newline = false;
}
if (multiline) {
multiline = false;
}
}
}).catch(function() {
if (process.stdin.isTTY) {
if (multiline) {
multiline = false;
}
}
}).finally(function() {
rl.setPrompt(prompt);
rl.prompt();
rl.resume();
});
} else {
continue_multiline(code);
}
} catch (e) {
console.error(e.message);
console.error(e.stack);
cmd = '';
rl.setPrompt(prompt);
rl.prompt();
}
});
}).catch(function(e) {
log_error('Internal Error: bootstrap filed');
log_error(e.message || e);
console.error('Internal Error: bootstrap filed');
});
}
// source: Node.js https://github.com/nodejs/node/blob/master/lib/internal/repl/history.js
function _writeToOutput(repl, message) {
repl._writeToOutput(message);
repl._refreshLine();
}
function setupHistory(repl, historyPath, ready) {
// Empty string disables persistent history
if (typeof historyPath === 'string')
historyPath = historyPath.trim();
if (historyPath === '') {
repl._historyPrev = _replHistoryMessage;
return ready(null, repl);
}
if (!historyPath) {
try {
historyPath = path.join(os.homedir(), '.lips_repl_history');
} catch (err) {
_writeToOutput(repl, '\nError: Could not get the home directory.\n' +
'REPL session history will not be persisted.\n');
debug(err.stack);
repl._historyPrev = _replHistoryMessage;
return ready(null, repl);
}
}
let timer = null;
let writing = false;
let pending = false;
repl.pause();
// History files are conventionally not readable by others:
// https://github.com/nodejs/node/issues/3392
// https://github.com/nodejs/node/pull/3394
fs.open(historyPath, 'a+', 0o0600, oninit);
function oninit(err, hnd) {
if (err) {
// Cannot open history file.
// Don't crash, just don't persist history.
_writeToOutput(repl, '\nError: Could not open history file.\n' +
'REPL session history will not be persisted.\n');
debug(err.stack);
repl._historyPrev = _replHistoryMessage;
repl.resume();
return ready(null, repl);
}
fs.close(hnd, onclose);
}
function onclose(err) {
if (err) {
return ready(err);
}
fs.readFile(historyPath, 'utf8', onread);
}
function onread(err, data) {
if (err) {
return ready(err);
}
if (data) {
repl.history = data.split(/[\n\r]+/, repl.historySize);
} else {
repl.history = [];
}
fs.open(historyPath, 'r+', onhandle);
}
function onhandle(err, hnd) {
if (err) {
return ready(err);
}
fs.ftruncate(hnd, 0, (err) => {
repl._historyHandle = hnd;
repl.on('line', online);
repl.once('exit', onexit);
// Reading the file data out erases it
repl.once('flushHistory', function() {
repl.resume();
ready(null, repl);
});
flushHistory();
});
}
// ------ history listeners ------
function online(line) {
repl._flushing = true;
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(flushHistory, kDebounceHistoryMS);
}
function flushHistory() {
timer = null;
if (writing) {
pending = true;
return;
}
writing = true;
const historyData = repl.history.join(os.EOL);
fs.write(repl._historyHandle, historyData, 0, 'utf8', onwritten);
}
function onwritten(err, data) {
writing = false;
if (pending) {
pending = false;
online();
} else {
repl._flushing = Boolean(timer);
if (!repl._flushing) {
repl.emit('flushHistory');
}
}
}
function onexit() {
if (repl._flushing) {
repl.once('flushHistory', onexit);
return;
}
repl.off('line', online);
fs.close(repl._historyHandle, () => {});
}
}
function _replHistoryMessage() {
if (this.history.length === 0) {
_writeToOutput(
this,
'\nPersistent history support disabled. Use user-writable path to enable.\n'
);
}
this._historyPrev = readline.Interface.prototype._historyPrev;
return this._historyPrev();
}