-
Notifications
You must be signed in to change notification settings - Fork 3
/
processes.js
76 lines (66 loc) · 1.73 KB
/
processes.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
const _ = require('lodash')
const prog = require('child_process')
const emitter = require('./emitter')
const kill = require('tree-kill')
const isWin = require('os').platform() === 'win32'
const processConfig = {
file: isWin ? process.env.comspec || 'cmd.exe' : '/bin/sh',
args: isWin ? ['/s', '/c'] : ['-c'],
}
const processes = {}
const killAllListenerRefs = {}
const deleteProcess = taskId => {
processes[taskId].pid = null
processes[taskId] = null
delete processes[taskId]
const emitterListeners = emitter._events.killall
if (emitterListeners && emitterListeners instanceof Array) {
emitterListeners.splice(killAllListenerRefs[taskId], 1)
}
delete killAllListenerRefs[taskId]
}
function killProcess(taskId) {
if (processes[taskId]) {
kill(processes[taskId].pid, 'SIGINT')
deleteProcess(taskId)
}
}
function attachKillListener(taskId) {
emitter.once('killall', () => killProcess(taskId))
killAllListenerRefs[taskId] = emitter.listeners('killall').length - 1
}
function getProcessById(taskId) {
return processes[taskId]
}
/**
* @param {object} command { id, rawTask, envs }
* @returns spawned process
*/
function createProcess({ id, rawTask, envs }, config) {
return (processes[id] = prog.spawn(
processConfig.file,
[...processConfig.args, rawTask],
{
stdio: 'pipe',
cwd: config.path.replace(/\\/g, '/'),
windowsVerbatimArguments: isWin,
env: _.assign(
{},
process.env,
{
PWD: config.path.replace(/\\/g, '/'),
},
// env variables from .env file
config.envs,
// env variables from command
envs
),
}
))
}
module.exports = {
killProcess,
attachKillListener,
getProcessById,
createProcess,
}