-
Notifications
You must be signed in to change notification settings - Fork 36
/
repl.js
executable file
·75 lines (64 loc) · 1.73 KB
/
repl.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
#!/usr/bin/env node
/*
repl.js
provides a repl for node that correctly sets up
js.io in the global scope so that you can run
jsio('import .foo') from the repl.
*/
var vm = require('vm');
//base jsio stuff
var jsio = require('./packages/jsio.js');
//this puts various jsio objects in the global namespace
jsio('from base import *');
//add these paths so we can use the built-in functionality
jsio.path.add('.');
jsio.path.add('./packages');
jsio('import preprocessors.cls as cls');
jsio('import preprocessors.import as importc');
//in the repl, or when running `jsio`, we want jsio to be global
global.jsio = jsio;
/*
* use a custom eval function to run the class and import preprocessors
* on code entered to the repl. This allows for 'import foo.bar' syntax
* as well as properly named Class intances.
*/
var preprocessEval = function(cmd, context, filename, callback) {
var src = cmd.toString();
if (src.match(/^\(.*\)/)) {
src = src.slice(1, cmd.length-2);
}
var def = {
path: filename,
src: src
};
cls(filename, def);
importc(filename, def);
var err, result;
try {
result = vm.runInThisContext(def.src, def.path);
} catch (e) {
err = e;
}
callback(err, result);
};
var startRepl = function() {
console.log('js.io repl starting\n');
//By passing global: true we use the existing global namespace. This means
//that our jsio environment that we set up will exist.
require('repl').start({
useGlobal: true,
eval: preprocessEval
});
};
if (process.argv.length > 2) {
var fs = require('fs');
var src = fs.readFileSync(process.argv[2]);
preprocessEval(src, null, process.argv[2], function(error, result) {
if (error) {
console.log(error.stack);
}
process.exit(error ? 1 : 0);
});
} else {
startRepl();
}