forked from graphql/graphql-js
-
Notifications
You must be signed in to change notification settings - Fork 5
/
utils.js
77 lines (67 loc) · 1.72 KB
/
utils.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
// @noflow
'use strict';
const fs = require('fs');
const util = require('util');
const path = require('path');
const childProcess = require('child_process');
function exec(command, options) {
const output = childProcess.execSync(command, {
maxBuffer: 10 * 1024 * 1024, // 10MB
encoding: 'utf-8',
...options,
});
return removeTrailingNewLine(output);
}
const childProcessExec = util.promisify(childProcess.exec);
async function execAsync(command, options) {
const output = await childProcessExec(command, {
maxBuffer: 10 * 1024 * 1024, // 10MB
encoding: 'utf-8',
...options,
});
return removeTrailingNewLine(output.stdout);
}
function removeTrailingNewLine(str) {
if (str == null) {
return str;
}
return str.split('\n').slice(0, -1).join('\n');
}
function rmdirRecursive(dirPath) {
if (fs.existsSync(dirPath)) {
for (const dirent of fs.readdirSync(dirPath, { withFileTypes: true })) {
const fullPath = path.join(dirPath, dirent.name);
if (dirent.isDirectory()) {
rmdirRecursive(fullPath);
} else {
fs.unlinkSync(fullPath);
}
}
fs.rmdirSync(dirPath);
}
}
function readdirRecursive(dirPath, opts = {}) {
const { ignoreDir } = opts;
const result = [];
for (const dirent of fs.readdirSync(dirPath, { withFileTypes: true })) {
const name = dirent.name;
if (!dirent.isDirectory()) {
result.push(dirent.name);
continue;
}
if (ignoreDir && ignoreDir.test(name)) {
continue;
}
const list = readdirRecursive(path.join(dirPath, name), opts).map((f) =>
path.join(name, f),
);
result.push(...list);
}
return result;
}
module.exports = {
exec,
execAsync,
rmdirRecursive,
readdirRecursive,
};