|
| 1 | +import fs = require('fs') |
1 | 2 | import repl = require('repl') // 'repl' here refers to the module named 'repl' in index.d.ts
|
2 |
| -import { createContext, parseError, runInContext } from '../index' |
| 3 | +import { createContext, IOptions, parseError, runInContext } from '../index' |
3 | 4 |
|
4 |
| -function startRepl(chapter = 1, useSubst: boolean) { |
| 5 | +function startRepl(chapter = 1, useSubst: boolean, prelude = '') { |
5 | 6 | // use defaults for everything
|
6 | 7 | const context = createContext(chapter)
|
7 |
| - repl.start( |
8 |
| - // the object being passed as argument fits the interface ReplOptions in the repl module. |
9 |
| - { |
10 |
| - eval: (cmd, unusedContext, unusedFilename, callback) => { |
11 |
| - runInContext(cmd, context, { scheduler: 'preemptive', useSubst }).then(obj => { |
12 |
| - if (obj.status === 'finished') { |
13 |
| - callback(null, obj.value) |
14 |
| - } else { |
15 |
| - callback(new Error(parseError(context.errors)), undefined) |
| 8 | + const options: Partial<IOptions> = { scheduler: 'preemptive', useSubst } |
| 9 | + runInContext(prelude, context, options).then(preludeResult => { |
| 10 | + if (preludeResult.status === 'finished') { |
| 11 | + console.log(preludeResult.value) |
| 12 | + repl.start( |
| 13 | + // the object being passed as argument fits the interface ReplOptions in the repl module. |
| 14 | + { |
| 15 | + eval: (cmd, unusedContext, unusedFilename, callback) => { |
| 16 | + runInContext(cmd, context, options).then(obj => { |
| 17 | + if (obj.status === 'finished') { |
| 18 | + callback(null, obj.value) |
| 19 | + } else { |
| 20 | + callback(new Error(parseError(context.errors)), undefined) |
| 21 | + } |
| 22 | + }) |
16 | 23 | }
|
17 |
| - }) |
18 |
| - } |
| 24 | + } |
| 25 | + ) |
| 26 | + } else { |
| 27 | + throw new Error(parseError(context.errors)) |
19 | 28 | }
|
20 |
| - ) |
| 29 | + }) |
21 | 30 | }
|
22 | 31 |
|
23 | 32 | function main() {
|
24 |
| - const chapter = process.argv.length > 2 ? parseInt(process.argv[2], 10) : 1 |
25 |
| - const useSubst = process.argv.length > 3 ? process.argv[3] === 'subst' : false |
26 |
| - startRepl(chapter, useSubst) |
| 33 | + const firstArg = process.argv[2] |
| 34 | + if (process.argv.length === 3 && String(Number(firstArg)) !== firstArg.trim()) { |
| 35 | + fs.readFile(firstArg, 'utf8', (err, data) => { |
| 36 | + if (err) { |
| 37 | + throw err |
| 38 | + } |
| 39 | + startRepl(4, false, data) |
| 40 | + }) |
| 41 | + } else { |
| 42 | + const chapter = process.argv.length > 2 ? parseInt(firstArg, 10) : 1 |
| 43 | + const useSubst = process.argv.length > 3 ? process.argv[3] === 'subst' : false |
| 44 | + startRepl(chapter, useSubst) |
| 45 | + } |
27 | 46 | }
|
28 | 47 |
|
29 | 48 | main()
|
0 commit comments