forked from q2ebanking/team-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathterminal.js
45 lines (37 loc) · 1.45 KB
/
terminal.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
const path = require('path')
const { platform } = require('os')
const { logger } = require('./logger')
const { spawn } = require('child_process')
const terminal = platform() === 'win32' ? 'powershell.exe' : 'bash'
const isVerbose = process.env.LOG_LEVEL === 'silly' || process.env.LOG_LEVEL === 'verbose'
const _cleanDataBuffer = dataBuffer => dataBuffer.toString('utf8').trim()
const _logBuffer = (dataBuffer, isError) => {
let lineItem = _cleanDataBuffer(dataBuffer)
if (lineItem.length > 0) {
if (isError) logger.error(lineItem)
else if (isVerbose) logger.verbose(lineItem)
}
}
const run = async (script, args, cwd) => {
return new Promise((resolve, reject) => {
let profiler = logger.startTimer()
let stdio = isVerbose ? ['inherit', 'pipe', 'pipe'] : 'inherit'
cwd = cwd || path.dirname(script)
let spawnParams = { shell: true, stdio, cwd }
logger.info(`Starting \`${script}\``)
let term = spawn(terminal, [script, args], spawnParams)
if (isVerbose) {
term.stdout.on('data', _logBuffer)
term.stderr.on('data', dataBuffer => _logBuffer(dataBuffer, true))
}
term.on('close', code => {
let level = code === 0 ? 'info' : 'error'
let message = `Done with \`${script}\``
if (code !== 0) message += ' with code ' + code
profiler.done({ message, level })
if (code === 0) resolve()
else reject(code)
})
})
}
module.exports = run