forked from react-native-community/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.ts
213 lines (184 loc) · 4.94 KB
/
helpers.ts
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
import fs from 'fs';
import os from 'os';
import path from 'path';
import {promisify} from 'util';
import {createDirectory} from 'jest-util';
// @ts-ignore jsfile
import rimraf from 'rimraf';
import execa from 'execa';
import chalk from 'chalk';
import slash from 'slash';
// @ts-ignore jsfile
import {Writable} from 'readable-stream';
const rimrafAsync = promisify(rimraf);
const CLI_PATH = path.resolve(__dirname, '../packages/cli/build/bin.js');
type RunOptions = {
nodeOptions?: string;
nodePath?: string;
timeout?: number; // kill the process after X milliseconds
expectedFailure?: boolean;
};
/**
* Helper function to run CLI command in a given folder
*/
export function runCLI(
dir: string,
args?: string[],
options: RunOptions = {
expectedFailure: false,
},
) {
return spawnScript(process.execPath, [CLI_PATH, ...(args || [])], {
...options,
cwd: dir,
});
}
// Runs cli until a given output is achieved, then kills it with `SIGTERM`
export async function runUntil(
dir: string,
args: string[] | undefined,
text: string,
options: RunOptions = {
expectedFailure: false,
},
) {
const spawnPromise = spawnScriptAsync(dir, args || [], {
timeout: 30000,
cwd: dir,
...options,
});
spawnPromise.stderr.pipe(
new Writable({
write(chunk: any, _encoding: string, callback: () => void) {
const output = chunk.toString('utf8');
if (output.includes(text)) {
spawnPromise.kill();
}
callback();
},
}),
);
return spawnPromise;
}
export const makeTemplate = (
str: string,
): ((values?: Array<any>) => string) => (values?: Array<any>) =>
str.replace(/\$(\d+)/g, (_match, number) => {
if (!Array.isArray(values)) {
throw new Error('Array of values must be passed to the template.');
}
return values[number - 1];
});
export const cleanup = (directory: string) => {
return rimrafAsync(directory);
};
export const cleanupSync = (directory: string) => {
rimraf.sync(directory);
};
/**
* Creates a nested directory with files and their contents
* writeFiles(
* '/home/tmp',
* {
* 'package.json': '{}',
* 'dir/file.js': 'module.exports = "x";',
* }
* );
*/
export const writeFiles = (
directory: string,
files: {[filename: string]: string},
) => {
createDirectory(directory);
Object.keys(files).forEach((fileOrPath) => {
const dirname = path.dirname(fileOrPath);
if (dirname !== '/') {
createDirectory(path.join(directory, dirname));
}
fs.writeFileSync(
path.resolve(directory, ...fileOrPath.split('/')),
files[fileOrPath],
);
});
};
export const copyDir = (src: string, dest: string) => {
const srcStat = fs.lstatSync(src);
if (srcStat.isDirectory()) {
if (!fs.existsSync(dest)) {
fs.mkdirSync(dest);
}
fs.readdirSync(src).map((filePath) =>
copyDir(path.join(src, filePath), path.join(dest, filePath)),
);
} else {
fs.writeFileSync(dest, fs.readFileSync(src));
}
};
export const getTempDirectory = (name: string) =>
path.resolve(os.tmpdir(), name);
type SpawnOptions = RunOptions & {
cwd: string;
};
type SpawnFunction<T> = (
execPath: string,
args: string[],
options: SpawnOptions,
) => T;
export const spawnScript: SpawnFunction<execa.ExecaReturns> = (
execPath,
args,
options,
) => {
const result = execa.sync(execPath, args, getExecaOptions(options));
handleTestFailure(execPath, options, result, args);
return result;
};
const spawnScriptAsync: SpawnFunction<execa.ExecaChildProcess> = (
execPath,
args,
options,
) => {
try {
return execa(execPath, args, getExecaOptions(options));
} catch (result) {
handleTestFailure(execPath, options, result, args);
return result;
}
};
function getExecaOptions(options: SpawnOptions) {
const isRelative = !path.isAbsolute(options.cwd);
const cwd = isRelative ? path.resolve(__dirname, options.cwd) : options.cwd;
const env = Object.assign({}, process.env, {FORCE_COLOR: '0'});
if (options.nodeOptions) {
env.NODE_OPTIONS = options.nodeOptions;
}
if (options.nodePath) {
env.NODE_PATH = options.nodePath;
}
return {
cwd,
env,
reject: false,
timeout: options.timeout || 0,
};
}
function handleTestFailure(
cmd: string,
options: SpawnOptions,
result: {[key: string]: any},
args: string[] | undefined,
) {
if (!options.expectedFailure && result.code !== 0) {
console.log(`Running ${cmd} command failed for unexpected reason. Here's more info:
${chalk.bold('cmd:')} ${cmd}
${chalk.bold('options:')} ${JSON.stringify(options)}
${chalk.bold('args:')} ${(args || []).join(' ')}
${chalk.bold('stderr:')} ${result.stderr}
${chalk.bold('stdout:')} ${result.stdout}
${chalk.bold('code:')} ${result.code}`);
}
}
export function replaceProjectRootInOutput(output: string, testFolder: string) {
const regex = new RegExp(`(:\\s").*(${slash(testFolder)})`, 'g');
return slash(output).replace(regex, '$1<<REPLACED_ROOT>>');
}