-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
284 lines (224 loc) · 7.97 KB
/
Copy pathindex.ts
File metadata and controls
284 lines (224 loc) · 7.97 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import cp, { ChildProcess } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import { WriteStream } from 'tty';
import { promisify } from 'util';
// module.exports = { spawn: p_spawn };
const fsAccess = promisify(fs.access);
const fsMkdir = promisify(fs.mkdir);
var defaultSpawnOpts: Options = {
};
interface Options {
/** The optional dir to execute the command */
cwd?: string;
/** (default true if no capture and no onStdout) If true stdio: ["pipe", process.stdio, process.stderr] */
toConsole?: boolean;
/** If set, the stdout and stderr will be forwarded to a file. If string, the folders will be created if needed, and the file will created as well (the old one will be deleted if present) */
toFile?: string;
/** (default false) If true, the fail will not thrown an error just resolve with .code non 0 */
ignoreFail?: boolean;
/** ["stdout","stderr"] if any of those set, it will get captured and returned (i.e. resolve as {stdout, stderr}) */
capture?: string | string[];
/** Optional input to be written to stdin */
input?: string;
/** forward of the stdout.on("data") to this function. This will turn stdio stdout to the default 'pipe' and therefore not printed to console */
onStdout?: (data: any) => void;
/** forward of the stderr.on("data") to this function. This will turn stdio stderr to the default 'pipe' and therefore not printed to console */
onStderr?: (data: any) => void;
shell?: boolean | string;
/**
* Any other child_process_options (https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options)
* if .stdio is set, the it will take precedence on the above
*/
[key: string]: any;
}
interface Result {
code: number;
stdout?: string;
stderr?: string;
}
/**
* Execute a spawn and return the Promise<Result>
*
* Usage:
* ```ts
* const result = await spawn('echo', ['hello','world'], {capture: 'stdout'});
* // result.stdout == "hello world"
* ```
*/
export async function spawn(cmd: string): Promise<Result>;
export async function spawn(cmd: string, args: string[]): Promise<Result>;
export async function spawn(cmd: string, options: Options): Promise<Result>;
export async function spawn(cmd: string, args: string[], options: Options): Promise<Result>;
export async function spawn(cmd: string, arg_1?: string[] | Options, arg_2?: Options): Promise<Result> {
return spawnCp(cmd, <any>arg_1, <any>arg_2)[0]; // widen type for passthrough
}
/**
* Execute the a spawn and return a tupple [Promise<Result>, ChildProcess] for full control
*/
export function spawnCp(cmd: string): [Promise<Result>, ChildProcess];
export function spawnCp(cmd: string, args: string[]): [Promise<Result>, ChildProcess];
export function spawnCp(cmd: string, options: Options): [Promise<Result>, ChildProcess];
export function spawnCp(cmd: string, args: string[], options: Options): [Promise<Result>, ChildProcess];
export function spawnCp(cmd: string, arg_1?: string[] | Options, arg_2?: Options): [Promise<Result>, ChildProcess] {
// get the eventual opts and build the spawn option
const args: string[] | undefined = (arg_1 && arg_1 instanceof Array) ? arg_1 : undefined;
const _opts: Options | undefined = (args) ? arg_2 : !(arg_1 instanceof Array) ? arg_1 : undefined;
const opts: Options = Object.assign({}, defaultSpawnOpts, _opts);
// if toConsole is undefined, set it to true if no capture or onStdout
if (opts.toConsole == null && !opts.capture && !opts.onStdout) {
opts.toConsole = true;
}
// build the spawn options
const cpOpts = extractCPOptions(opts) || {};
// make sure it is an array if defined
const capture = (opts.capture && typeof opts.capture === "string") ? [opts.capture] : opts.capture;
const stdoutData = (capture && capture.includes("stdout")) ? [] : null;
const stderrData = (capture && capture.includes("stderr")) ? [] : null;
let stdout: string | number | WriteStream = "pipe";
let stderr: string | number | WriteStream = "pipe";
// Note: for now use the fs sync operation (should be fast anyway)
if (opts.toFile) {
opts.toConsole = false; // can only one or the other.
let toFileInfo = path.parse(opts.toFile);
fs.mkdirSync(toFileInfo.dir);
try {
if (fs.statSync(opts.toFile).isFile()) {
fs.unlinkSync(opts.toFile);
}
} catch (ex) { } // do nothing if does not exist
stdout = fs.openSync(opts.toFile, "a");
stderr = fs.openSync(opts.toFile, "a");
}
// If we have toConsole and no capture and no onStd binding, we output to std
if (opts.toConsole && !opts.onStdout && stdoutData == null) {
stdout = process.stdout;
}
// If we have toConsole and no capture and no onStd binding, we output to std
if (opts.toConsole && !opts.onStderr && stderrData == null) {
stderr = process.stderr;
}
// the passed stdio will aways take precedence
var stdio = cpOpts.stdio || ["pipe", stdout, stderr];
cpOpts.stdio = stdio;
cpOpts.shell = opts.shell;
let ps: ChildProcess | undefined;
const promise = new Promise<Result>(function (resolve, reject) {
// build the params list depending of what has been defined
// TODO: Needs to have the right types (still does not below with the cp.spawn.apply)
const params: (string | readonly string[] | cp.SpawnOptionsWithoutStdio)[] = [cmd];
if (args) {
params.push(args);
}
if (cpOpts) {
params.push(cpOpts);
}
// if we have the toConsole
if (opts.toConsole) {
console.log(">>> Will execute: " + fullCmd(cmd, args));
if (cpOpts && cpOpts.cwd) {
console.log(" from dir: " + cpOpts.cwd);
}
}
// TODO: needs to fix the type to not have to cast to any
ps = cp.spawn.apply(cp, params as any);
if (opts?.input) {
ps.stdin?.write(opts.input);
ps.stdin?.end();
}
if (ps.stdout) {
ps.stdout.on("data", (data: any) => {
stdHandler(data, opts.onStdout, stdoutData, (opts.toConsole) ? process.stdout : null);
});
}
if (ps.stderr) {
ps.stderr.on("data", (data: any) => {
stdHandler(data, opts.onStderr, stderrData, (opts.toConsole) ? process.stderr : null);
});
}
ps.on('close', (code: number) => {
if (!opts.ignoreFail && code !== 0) {
reject(new Error(`ERROR - Exit code ${code} - for command: ` + fullCmd(cmd, args)));
} else {
const r: any = { code: code };
if (stdoutData != null) {
r.stdout = stdoutData.join("");
}
if (stderrData != null) {
r.stderr = stderrData.join("");
}
resolve(r);
}
});
ps.on("error", (err: any) => {
reject(err);
});
});
return [promise, ps!];
}
// TOOD: Need to type
function stdHandler(data: any, onStd: any, stdData: any, processStd: any) {
// if we have a onStd...
if (onStd) {
onStd(data);
}
// if we need to capture the data
if (stdData != null) {
stdData.push(data.toString());
}
// if we have a processStd (because of toConsole was set, we write the datda)
if (processStd) {
processStd.write(data);
}
}
function fullCmd(cmd: string, args?: string[]) {
if (args) {
cmd += " " + args.join(" ");
}
return cmd;
}
const spawnOptionNames = { "cwd": true, "env": true, "argv0": true, "stdio": true, "detached": true, "uid": true, "gid": true, "shell": true };
function extractCPOptions(opts: Options) {
if (!opts) {
return;
}
// TODO: need to type
const cpOpts: any = {};
let hasVal = false;
for (let key in opts) {
if ((<any>spawnOptionNames)[key]) {
const v = opts[key];
if (v != null) {
hasVal = true;
cpOpts[key] = v;
}
}
}
if (hasVal) {
return cpOpts;
}
}
// --------- File Utils --------- //
// Create all the missing path for this folder
async function fsMkdirs(folderPath: string) {
var folders = [];
var tmpPath = path.normalize(folderPath);
var exists = await fsExists(tmpPath);
while (!exists) {
folders.push(tmpPath);
tmpPath = path.join(tmpPath, '..');
exists = await fsExists(tmpPath);
}
for (var i = folders.length - 1; i >= 0; i--) {
await fsMkdir(folders[i]);
}
}
async function fsExists(path: string) {
try {
await fsAccess(path);
return true;
} catch (ex) {
return false;
}
}
// --------- /File Utils --------- //