-
-
Notifications
You must be signed in to change notification settings - Fork 360
Expand file tree
/
Copy pathcli.mjs
More file actions
executable file
·397 lines (353 loc) · 14.7 KB
/
cli.mjs
File metadata and controls
executable file
·397 lines (353 loc) · 14.7 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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
#!/usr/bin/env node
'use strict';
import { execSync, execFileSync, spawn } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import { argv, env } from 'process';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
if (argv.length < 3) {
console.error(`Usage: ${path.basename(__filename)} <platform>`);
process.exit(1);
}
const platform = argv[2];
if (platform !== 'ios' && platform !== 'android') {
console.error(`Unsupported platform: ${platform}`);
process.exit(1);
}
var actions = ['create', 'build', 'test'];
if (argv.length >= 4) {
var newActions = [];
for (let index = 0; index < actions.length; index++) {
const action = actions[index];
if (argv.includes(`--${action}`) || argv.includes(`-${action}`) || argv.includes(action)) {
newActions.push(action);
}
}
actions = newActions;
}
console.log(`Performing actions: ${actions}`);
if (env.SENTRY_DISABLE_AUTO_UPLOAD === undefined) {
// Auto upload to prod made the CI flaky
// This can be removed in the future or when mocked server is added
env.SENTRY_DISABLE_AUTO_UPLOAD = 'true';
}
if (env.PRODUCTION === undefined && env.CI == undefined) {
// When executed locally and PROD not specified most likely we wanted production build
env.PRODUCTION = 1;
}
if (!env.USE_FRAMEWORKS || env.USE_FRAMEWORKS === 'no') {
// In case it's set to an empty string, it causes issues in Podfile.
delete env.USE_FRAMEWORKS;
}
const e2eDir = path.resolve(__dirname);
const e2eTestPackageName = JSON.parse(fs.readFileSync(`${e2eDir}/package.json`, 'utf8')).name;
const patchScriptsDir = path.resolve(e2eDir, 'patch-scripts');
const workspaceRootDir = path.resolve(__dirname, '../..');
const corePackageDir = path.resolve(workspaceRootDir, 'packages/core');
const corePackageJson = JSON.parse(fs.readFileSync(`${corePackageDir}/package.json`, 'utf8'));
const RNVersion = env.RN_VERSION ? env.RN_VERSION : corePackageJson.devDependencies['react-native'];
const RNEngine = env.RN_ENGINE ? env.RN_ENGINE : 'hermes';
const buildType = env.PRODUCTION ? 'Release' : 'Debug';
const appSourceRepo = 'https://github.com/react-native-community/rn-diff-purge.git';
const appRepoDir = `${e2eDir}/react-native-versions/${RNVersion}`;
const appName = 'RnDiffApp';
const appDir = `${appRepoDir}/${appName}`;
const testAppName = `${appName}.${platform === 'ios' ? 'app' : 'apk'}`;
const testApp = `${e2eDir}/${testAppName}`;
const appId = platform === 'ios' ? 'org.reactjs.native.example.RnDiffApp' : 'com.rndiffapp';
const sentryAuthToken = env.SENTRY_AUTH_TOKEN;
function runCodegenIfNeeded(rnVersion, platform, appDir) {
const versionNumber = parseFloat(rnVersion.replace(/[^\d.]/g, ''));
const shouldRunCodegen = platform === 'android' && versionNumber >= 0.80;
if (shouldRunCodegen) {
console.log(`Running codegen for React Native ${rnVersion}...`);
try {
execSync('./gradlew generateCodegenArtifactsFromSchema', {
stdio: 'inherit',
cwd: path.join(appDir, 'android'),
env: env
});
console.log('Gradle codegen task completed successfully');
} catch (error) {
console.error('Codegen failed:', error.message);
}
} else {
console.log(`Skipping codegen for React Native ${rnVersion}`);
}
}
function patchBoostIfNeeded(rnVersion, patchScriptsDir) {
const versionNumber = parseFloat(rnVersion.replace(/[^\d.]/g, ''));
const shouldPatchBoost = platform === 'ios' && versionNumber <= 0.80;
if (!shouldPatchBoost) {
console.log(`Skipping boost patch for React Native ${rnVersion}`);
return;
}
execSync(`${patchScriptsDir}/rn.patch.boost.js --podspec node_modules/react-native/third-party-podspecs/boost.podspec`, {
stdio: 'inherit',
cwd: appDir,
env: env,
});
}
// Build and publish the SDK - we only need to do this once in CI.
// Locally, we may want to get updates from the latest build so do it on every app build.
if (actions.includes('create') || (env.CI === undefined && actions.includes('build'))) {
execSync(`yarn build`, { stdio: 'inherit', cwd: workspaceRootDir, env: env });
execSync(`yalc publish --private`, { stdio: 'inherit', cwd: e2eDir, env: env });
execSync(`yalc publish`, { stdio: 'inherit', cwd: corePackageDir, env: env });
}
if (actions.includes('create')) {
// Clone the test app repo
if (fs.existsSync(appRepoDir)) fs.rmSync(appRepoDir, { recursive: true });
execSync(`git clone ${appSourceRepo} --branch release/${RNVersion} --single-branch ${appRepoDir}`, {
stdio: 'inherit',
env: env,
});
// Install dependencies
// yalc add doesn't fail if the package is not found - it skips silently.
let yalcAddOutput = execSync(`yalc add @sentry/react-native`, { cwd: appDir, env: env, encoding: 'utf-8' });
if (!yalcAddOutput.match(/Package .* added ==>/)) {
console.error(yalcAddOutput);
process.exit(1);
} else {
console.log(yalcAddOutput.trim());
}
yalcAddOutput = execSync(`yalc add ${e2eTestPackageName}`, { cwd: appDir, env: env, encoding: 'utf-8' });
if (!yalcAddOutput.match(/Package .* added ==>/)) {
console.error(yalcAddOutput);
process.exit(1);
} else {
console.log(yalcAddOutput.trim());
}
// original yarnrc contains the exact yarn version which causes corepack to fail to install yarn v3
fs.writeFileSync(`${appDir}/.yarnrc.yml`, 'nodeLinker: node-modules', { encoding: 'utf-8' });
// yarn v3 won't install dependencies in a sub project without a yarn.lock file present
fs.writeFileSync(`${appDir}/yarn.lock`, '');
execSync(`yarn install`, {
stdio: 'inherit',
cwd: appDir,
// yarn v3 run immutable install by default in CI
env: Object.assign(env, { YARN_ENABLE_IMMUTABLE_INSTALLS: false }),
});
execSync(`yarn add react-native-launch-arguments@4.0.2`, {
stdio: 'inherit',
cwd: appDir,
// yarn v3 run immutable install by default in CI
env: Object.assign(env, { YARN_ENABLE_IMMUTABLE_INSTALLS: false }),
});
// Patch react-native-launch-arguments for Gradle 9+ compatibility (Android) and React Native 0.84+ compatibility (iOS)
execSync(`${patchScriptsDir}/rn.patch.launch-arguments.js --app-dir .`, {
stdio: 'inherit',
cwd: appDir,
env: env,
});
// Patch the app
execSync(`patch --verbose --strip=0 --force --ignore-whitespace --fuzz 4 < ${patchScriptsDir}/rn.patch`, {
stdio: 'inherit',
cwd: appDir,
env: env,
});
execSync(`${patchScriptsDir}/rn.patch.app.js --app .`, { stdio: 'inherit', cwd: appDir, env: env });
execSync(`${patchScriptsDir}/rn.patch.metro.config.js --path metro.config.js`, {
stdio: 'inherit',
cwd: appDir,
env: env,
});
// Patch boost
patchBoostIfNeeded(RNVersion, patchScriptsDir);
// Set up platform-specific app configuration
if (platform === 'ios') {
execSync('ruby --version', { stdio: 'inherit', cwd: `${appDir}`, env: env });
execSync(`${patchScriptsDir}/rn.patch.podfile.js --pod-file Podfile --engine ${RNEngine}`, {
stdio: 'inherit',
cwd: `${appDir}/ios`,
env: env,
});
// Clean Pods to ensure CocoaPods reads the patched podspec
if (fs.existsSync(`${appDir}/ios/Pods`)) {
fs.rmSync(`${appDir}/ios/Pods`, { recursive: true });
}
if (fs.existsSync(`${appDir}/ios/Podfile.lock`)) {
fs.rmSync(`${appDir}/ios/Podfile.lock`);
}
if (fs.existsSync(`${appDir}/Gemfile`)) {
execSync(`bundle install`, { stdio: 'inherit', cwd: appDir, env: env });
execSync('bundle exec pod install --repo-update', { stdio: 'inherit', cwd: `${appDir}/ios`, env: env });
} else {
execSync('pod install --repo-update', { stdio: 'inherit', cwd: `${appDir}/ios`, env: env });
}
execSync('cat Podfile.lock | grep RNSentry', { stdio: 'inherit', cwd: `${appDir}/ios`, env: env });
execSync(
`${patchScriptsDir}/rn.patch.xcode.js --project ios/${appName}.xcodeproj/project.pbxproj --rn-version ${RNVersion}`,
{ stdio: 'inherit', cwd: appDir, env: env },
);
} else if (platform === 'android') {
execSync(
`${patchScriptsDir}//rn.patch.gradle.properties.js --gradle-properties android/gradle.properties --engine ${RNEngine}`,
{ stdio: 'inherit', cwd: appDir, env: env },
);
execSync(`${patchScriptsDir}/rn.patch.app.build.gradle.js --app-build-gradle android/app/build.gradle`, {
stdio: 'inherit',
cwd: appDir,
env: env,
});
if (env.RCT_NEW_ARCH_ENABLED) {
execSync(`perl -i -pe's/newArchEnabled=false/newArchEnabled=true/g' android/gradle.properties`, {
stdio: 'inherit',
cwd: appDir,
env: env,
});
console.log('New Architecture enabled');
}
}
}
if (actions.includes('build')) {
console.log(`Building ${platform}: ${buildType}`);
var appProduct;
if (platform === 'ios') {
// Build iOS test app
execSync(
`set -o pipefail && xcodebuild \
-workspace ${appName}.xcworkspace \
-configuration ${buildType} \
-scheme ${appName} \
-sdk 'iphonesimulator' \
-destination 'generic/platform=iOS Simulator' \
ONLY_ACTIVE_ARCH=yes \
-derivedDataPath DerivedData \
build | tee xcodebuild.log | xcbeautify`,
{ stdio: 'inherit', cwd: `${appDir}/ios`, env: env },
);
appProduct = `${appDir}/ios/DerivedData/Build/Products/${buildType}-iphonesimulator/${appName}.app`;
} else if (platform === 'android') {
runCodegenIfNeeded(RNVersion, platform, appDir);
execSync(`./gradlew assemble${buildType} -PreactNativeArchitectures=x86 --no-daemon`, {
stdio: 'inherit',
cwd: `${appDir}/android`,
env: env,
});
appProduct = `${appDir}/android/app/build/outputs/apk/release/app-release.apk`;
}
console.log(`Moving ${appProduct} to ${testApp}`);
if (fs.existsSync(testApp)) fs.rmSync(testApp, { recursive: true });
fs.renameSync(appProduct, testApp);
}
if (actions.includes('test')) {
// Run e2e tests
if (platform === 'ios') {
try {
execSync('xcrun simctl list devices | grep -q "(Booted)"');
} catch (error) {
throw new Error('No simulator is currently booted. Please boot a simulator before running this script.');
}
execFileSync('xcrun', ['simctl', 'install', 'booted', testApp]);
} else if (platform === 'android') {
try {
execSync('adb devices | grep -q "emulator"');
} catch (error) {
throw new Error('No Android emulator is currently running. Please start an emulator before running this script.');
}
execFileSync('adb', ['install', '-r', '-d', testApp]);
}
if (!sentryAuthToken) {
console.log('Skipping maestro test due to unavailable or empty SENTRY_AUTH_TOKEN');
} else {
const maestroDir = path.join(e2eDir, 'maestro');
const flowFiles = fs.readdirSync(maestroDir)
.filter(f => f.endsWith('.yml') && !f.startsWith('utils'))
.sort((a, b) => {
// Run crash.yml last — it kills the app via nativeCrash(), and
// post-crash simulator state can be flaky on Cirrus Labs Tart VMs.
if (a === 'crash.yml') return 1;
if (b === 'crash.yml') return -1;
return a.localeCompare(b);
});
console.log(`Discovered ${flowFiles.length} Maestro flows: ${flowFiles.join(', ')}`);
// Warm up Maestro's driver connection before running test flows.
// The first Maestro launchApp after simulator boot can fail on Cirrus
// Labs Tart VMs because the IDB/XCUITest driver isn't fully connected.
// Running a lightweight warmup flow ensures the driver is ready.
const warmupFlow = path.join('maestro', 'utils', 'warmup.yml');
console.log('Warming up Maestro driver...');
try {
execFileSync('maestro', [
'test',
warmupFlow,
'--env', `APP_ID=${appId}`,
'--env', `SENTRY_AUTH_TOKEN=${sentryAuthToken}`,
], {
stdio: 'pipe',
cwd: e2eDir,
});
} catch (error) {
console.warn('Maestro driver warm-up failed (non-fatal, continuing with tests)');
}
const results = [];
// Run each flow in its own process to prevent crash cascade —
// when crash.yml kills the app, a shared Maestro session would fail
// all subsequent flows.
console.log('Waiting for flows to complete...');
for (const flow of flowFiles) {
const flowPath = path.join('maestro', flow);
const startTime = Date.now();
try {
execFileSync('maestro', [
'test',
flowPath,
'--env', `APP_ID=${appId}`,
'--env', `SENTRY_AUTH_TOKEN=${sentryAuthToken}`,
'--debug-output', 'maestro-logs',
'--flatten-debug-output',
], {
stdio: 'pipe',
cwd: e2eDir,
});
const elapsed = Math.round((Date.now() - startTime) / 1000);
const name = flow.replace('.yml', '');
results.push({ name, passed: true, elapsed });
console.log(`[Passed] ${name} (${elapsed}s)`);
} catch (error) {
const elapsed = Math.round((Date.now() - startTime) / 1000);
const name = flow.replace('.yml', '');
const output = (error.stdout?.toString() || '') + (error.stderr?.toString() || '');
const detail = output.split('\n').find(l =>
l.includes('App crashed') || l.includes('Element not found') || l.includes('FAILED')) || '';
results.push({ name, passed: false, elapsed, detail });
console.log(`[Failed] ${name} (${elapsed}s)${detail ? ` (${detail.trim()})` : ''}`);
// Dump Maestro output for failed flows to aid debugging
if (output) {
console.log(`\n--- ${name} output ---\n${output.trim()}\n--- end ${name} output ---\n`);
}
}
}
const failedFlows = results.filter(r => !r.passed).map(r => r.name);
// Always redact sensitive data, even if some tests failed
try {
const logDir = path.join(e2eDir, 'maestro-logs');
if (fs.existsSync(logDir)) {
const redactFiles = (dir) => {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
redactFiles(fullPath);
} else {
const content = fs.readFileSync(fullPath, 'utf8');
if (content.includes(sentryAuthToken)) {
fs.writeFileSync(fullPath, content.replaceAll(sentryAuthToken, '[REDACTED]'));
}
}
}
};
redactFiles(logDir);
console.log('Redacted sensitive data from logs');
}
} catch (error) {
console.warn('Failed to redact sensitive data from logs:', error.message);
}
if (failedFlows.length > 0) {
console.error(`\nFailed flows: ${failedFlows.join(', ')}`);
process.exit(1);
}
}
}