generated from actions/javascript-action
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
91 lines (76 loc) · 2.15 KB
/
index.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
const core = require('@actions/core');
const process = require('process');
const { Buffer } = require('buffer');
const { Transform } = require('stream');
const { spawn } = require('child_process');
const options = {
bash: ['--noprofile', '--norc', '-eo', 'pipefail', '-c'],
sh: ['-e', '-c'],
python: ['-c'],
pwsh: ['-command', '.'],
powershell: ['-command', '.']
}
class RecordStream extends Transform {
constructor () {
super()
this._data = Buffer.from([])
}
get output () {
return this._data
}
parse() {
const text = this.output.toString();
try {
return JSON.parse(text);
}
catch (e) {
return text
}
}
_transform (chunk, _, callback) {
this._data = Buffer.concat([this._data, chunk])
callback(null, chunk)
}
}
function exec(shell, command, workspace) {
return new Promise((resolve, reject) => {
// prepare the streams
const stdout = new RecordStream();
const stderr = new RecordStream();
// prepare the shell arguments
const args = [...options[shell], command];
// prepare the process options
const opts = { env: process.env, cwd: workspace ?? process.cwd() };
// spawn the process
const task = spawn(shell, args, opts);
// Record stream output and pass it through main process
task.stdout.pipe(stdout).pipe(process.stdout);
task.stderr.pipe(stderr).pipe(process.stderr);
task.on('error', error => reject(error))
task.on('close', code => {
core.setOutput('stdout', stdout.parse());
core.setOutput('stderr', stderr.parse());
if (code === 0) {
resolve();
} else {
reject(new Error(`Process completed with exit code ${code}.`));
}
})
})
}
// most @actions toolkit packages have async methods
async function run() {
try {
const command = core.getInput('run');
if (!command) {
throw new Error(`option "run" must be one provided.`);
}
const shell = core.getInput('shell');
const workspace = core.getInput("working-directory");
// execute the command
await exec(shell, command, workspace);
} catch (error) {
core.setFailed(error.message);
}
}
run();