Save last execution result in for REPL (#2843)

This commit is contained in:
Kevin (Kun) "Kassimo" Qian 2019-08-30 23:45:35 -07:00 committed by Ryan Dahl
parent 54a3b54138
commit 07c3c76d0d
2 changed files with 16 additions and 0 deletions

View file

@ -25,6 +25,7 @@ function replError(...args: unknown[]): void {
} }
const helpMsg = [ const helpMsg = [
"_ Print last execution output",
"exit Exit the REPL", "exit Exit the REPL",
"help Print this help message" "help Print this help message"
].join("\n"); ].join("\n");
@ -71,10 +72,15 @@ function isRecoverableError(e: Error): boolean {
// Evaluate code. // Evaluate code.
// Returns true if code is consumed (no error/irrecoverable error). // Returns true if code is consumed (no error/irrecoverable error).
// Also attempts setting window._ to last valid execute output.
// Returns false if error is recoverable // Returns false if error is recoverable
function evaluate(code: string): boolean { function evaluate(code: string): boolean {
const [result, errInfo] = core.evalContext(code); const [result, errInfo] = core.evalContext(code);
if (!errInfo) { if (!errInfo) {
// Try setting `window._` to the returned result
try {
window._ = result;
} catch {} // Silently fail on error.
replLog(result); replLog(result);
} else if (errInfo.isCompileError && isRecoverableError(errInfo.thrown)) { } else if (errInfo.isCompileError && isRecoverableError(errInfo.thrown)) {
// Recoverable compiler error // Recoverable compiler error
@ -107,6 +113,9 @@ export async function replLoop(): Promise<void> {
exit(exitCode); exit(exitCode);
}; };
// Make _ a valid property on window to avoid confusing error.
window._ = undefined;
while (true) { while (true) {
let code = ""; let code = "";
// Top level read // Top level read

View file

@ -58,6 +58,7 @@ class TestRepl(DenoTestCase):
def test_help_command(self): def test_help_command(self):
out, err, code = self.input("help") out, err, code = self.input("help")
expectedOut = '\n'.join([ expectedOut = '\n'.join([
"_ Print last execution output",
"exit Exit the REPL", "exit Exit the REPL",
"help Print this help message", "help Print this help message",
"", "",
@ -150,6 +151,12 @@ class TestRepl(DenoTestCase):
self.assertTrue(err.startswith("Unable to save REPL history:")) self.assertTrue(err.startswith("Unable to save REPL history:"))
self.assertEqual(code, 0) self.assertEqual(code, 0)
def test_save_last_output(self):
out, err, code = self.input("1", "_")
self.assertEqual(out, '1\n1\n')
self.assertEqual(err, '')
self.assertEqual(code, 0)
if __name__ == "__main__": if __name__ == "__main__":
run_tests() run_tests()