-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathssl.js
95 lines (91 loc) · 2.29 KB
/
ssl.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
const isolate = require('./lib/isolate')
const util = require('./lib/util')
const cp = require('child_process')
var langStore = null
function loadLangaugeSync () {
langStore = new Map()
let files = util.lsSync('lib/langauge')
files = files.filter(y => /\w+\.js$/.exec(y))
for (let i of files) {
let langName = i.slice(0, -3)
let langModule = require('./lib/langauge/' + langName)
langStore.set(langName, langModule)
}
}
function init (boxId) {
return isolate(['--cg', '--init', '--box-id', boxId])
.then(result => {
return result.stdout.trim()
})
}
function writeSource (dir, code, file) {
const path = dir + '/' + file
return util.writeFile(path, code)
}
function writeStdinFile (dir, stdin) {
const path = dir + '/_in'
return util.writeFile(path, stdin)
}
function compile (des, compiler) {
const cmd = compiler(des)
return new Promise((resolve, reject) => {
cp.exec(cmd, (err, stdout, stderr) => {
if (err)reject(err)
else resolve({stdout: stdout, stderr: stderr})
})
})
}
function clean (boxId) {
return isolate(['--cleanup', '--box-id', boxId])
}
function run (boxId, executor) {
return isolate([
'--box-id', boxId,
'-p',
'--cg',
'--stdin', '_in',
'--run',
'--',
...executor])
}
function ssl (options) {
const {source_code, langauge, stdin = ''} = options
var isolateDirectory
var langaugeModule
var p
if (!langStore.has(langauge)) {
let error = new Error('langauge not support')
p = Promise.reject(error)
} else {
langaugeModule = langStore.get(langauge)
p = Promise.resolve()
}
const isolateBoxId = util.generateBoxId()
return p
.then(() => {
return init(isolateBoxId)
})
.then(dir => {
isolateDirectory = dir + '/box'
return writeSource(isolateDirectory, source_code, langaugeModule.sourceFileName)
})
.then(() => {
return compile(isolateDirectory, langaugeModule.compile)
})
.then(() => {
return writeStdinFile(isolateDirectory, stdin)
})
.then(() => {
return run(isolateBoxId, langaugeModule.execute)
})
.then(x => {
return clean(isolateBoxId)
.then(() => x.stdout)
})
.catch(e => {
console.error('error', e)
return Promise.reject(e)
})
}
loadLangaugeSync()
module.exports = ssl