-
Notifications
You must be signed in to change notification settings - Fork 906
/
index.ts
629 lines (552 loc) · 16.4 KB
/
index.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
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import child_process from 'child_process';
import path from 'path';
import fs from 'fs';
import chalk from 'chalk';
import {Config, IOSProjectInfo} from '@react-native-community/cli-types';
import {getDestinationSimulator} from '../../tools/getDestinationSimulator';
import {logger, CLIError, link} from '@react-native-community/cli-tools';
import {BuildFlags, buildProject} from '../buildIOS/buildProject';
import {iosBuildOptions} from '../buildIOS';
import {Device} from '../../types';
import listIOSDevices from '../../tools/listIOSDevices';
import {checkIfConfigurationExists} from '../../tools/checkIfConfigurationExists';
import {getProjectInfo} from '../../tools/getProjectInfo';
import {getConfigurationScheme} from '../../tools/getConfigurationScheme';
import {selectFromInteractiveMode} from '../../tools/selectFromInteractiveMode';
import {promptForDeviceSelection} from '../../tools/prompts';
import getSimulators from '../../tools/getSimulators';
export interface FlagsT extends BuildFlags {
simulator?: string;
configuration: string;
scheme?: string;
projectPath: string;
device?: string | true;
udid?: string;
binaryPath?: string;
listDevices?: boolean;
}
async function runIOS(_: Array<string>, ctx: Config, args: FlagsT) {
link.setPlatform('ios');
if (ctx.reactNativeVersion !== 'unknown') {
link.setVersion(ctx.reactNativeVersion);
}
if (!ctx.project.ios) {
throw new CLIError(
'iOS project folder not found. Are you sure this is a React Native project?',
);
}
const {xcodeProject, sourceDir} = ctx.project.ios;
if (!xcodeProject) {
throw new CLIError(
`Could not find Xcode project files in "${sourceDir}" folder`,
);
}
process.chdir(sourceDir);
if (args.binaryPath) {
args.binaryPath = path.isAbsolute(args.binaryPath)
? args.binaryPath
: path.join(ctx.root, args.binaryPath);
if (!fs.existsSync(args.binaryPath)) {
throw new CLIError(
'binary-path was specified, but the file was not found.',
);
}
}
if (args.configuration) {
logger.warn('--configuration has been deprecated. Use --mode instead.');
logger.warn(
'Parameters were automatically reassigned to --mode on this run.',
);
args.mode = args.configuration;
}
const projectInfo = getProjectInfo();
if (args.mode) {
checkIfConfigurationExists(projectInfo, args.mode);
}
const inferredSchemeName = path.basename(
xcodeProject.name,
path.extname(xcodeProject.name),
);
let scheme = args.scheme || inferredSchemeName;
let mode = args.mode;
if (args.interactive) {
const selection = await selectFromInteractiveMode({scheme, mode});
if (selection.scheme) {
scheme = selection.scheme;
}
if (selection.mode) {
mode = selection.mode;
}
}
const modifiedArgs = {...args, scheme, mode};
modifiedArgs.mode = getConfigurationScheme(
{scheme: modifiedArgs.scheme, mode: modifiedArgs.mode},
sourceDir,
);
logger.info(
`Found Xcode ${
xcodeProject.isWorkspace ? 'workspace' : 'project'
} "${chalk.bold(xcodeProject.name)}"`,
);
const availableDevices = await listIOSDevices();
if (modifiedArgs.listDevices || modifiedArgs.interactive) {
if (modifiedArgs.device || modifiedArgs.udid) {
logger.warn(
`Both ${
modifiedArgs.device ? 'device' : 'udid'
} and "list-devices" parameters were passed to "run" command. We will list available devices and let you choose from one.`,
);
}
const selectedDevice = await promptForDeviceSelection(availableDevices);
if (!selectedDevice) {
throw new CLIError(
`Failed to select device, please try to run app without ${
args.listDevices ? 'list-devices' : 'interactive'
} command.`,
);
}
if (selectedDevice.type === 'simulator') {
return runOnSimulator(xcodeProject, scheme, modifiedArgs, selectedDevice);
} else {
return runOnDevice(selectedDevice, scheme, xcodeProject, modifiedArgs);
}
}
if (!modifiedArgs.device && !modifiedArgs.udid && !modifiedArgs.simulator) {
const bootedDevices = availableDevices.filter(
({type, isAvailable}) => type === 'device' && isAvailable,
);
const simulators = getSimulators();
const bootedSimulators = Object.keys(simulators.devices)
.map((key) => simulators.devices[key])
.reduce((acc, val) => acc.concat(val), [])
.filter(({state}) => state === 'Booted');
const booted = [...bootedDevices, ...bootedSimulators];
if (booted.length === 0) {
logger.info(
'No booted devices or simulators found. Launching first available simulator...',
);
return runOnSimulator(xcodeProject, scheme, modifiedArgs);
}
logger.info(`Found booted ${booted.map(({name}) => name).join(', ')}`);
return runOnBootedDevicesSimulators(
scheme,
xcodeProject,
modifiedArgs,
bootedDevices,
bootedSimulators,
);
}
if (modifiedArgs.device && modifiedArgs.udid) {
return logger.error(
'The `device` and `udid` options are mutually exclusive.',
);
}
if (modifiedArgs.udid) {
const device = availableDevices.find((d) => d.udid === modifiedArgs.udid);
if (!device) {
return logger.error(
`Could not find a device with udid: "${chalk.bold(
modifiedArgs.udid,
)}". ${printFoundDevices(availableDevices)}`,
);
}
if (device.type === 'simulator') {
return runOnSimulator(xcodeProject, scheme, modifiedArgs);
} else {
return runOnDevice(device, scheme, xcodeProject, modifiedArgs);
}
} else if (modifiedArgs.device) {
const physicalDevices = availableDevices.filter(
({type}) => type !== 'simulator',
);
const device = matchingDevice(physicalDevices, modifiedArgs.device);
if (device) {
return runOnDevice(device, scheme, xcodeProject, modifiedArgs);
}
} else {
runOnSimulator(xcodeProject, scheme, modifiedArgs);
}
}
async function runOnBootedDevicesSimulators(
scheme: string,
xcodeProject: IOSProjectInfo,
args: FlagsT,
devices: Device[],
simulators: Device[],
) {
for (const device of devices) {
await runOnDevice(device, scheme, xcodeProject, args);
}
for (const simulator of simulators) {
await runOnSimulator(xcodeProject, scheme, args, simulator);
}
}
async function runOnSimulator(
xcodeProject: IOSProjectInfo,
scheme: string,
args: FlagsT,
simulator?: Device,
) {
// let selectedSimulator;
/**
* If provided simulator does not exist, try simulators in following order
* - iPhone 14
* - iPhone 13
* - iPhone 12
* - iPhone 11
*/
let selectedSimulator;
if (simulator) {
selectedSimulator = simulator;
} else {
const fallbackSimulators = [
'iPhone 14',
'iPhone 13',
'iPhone 12',
'iPhone 11',
];
selectedSimulator = getDestinationSimulator(args, fallbackSimulators);
}
if (!selectedSimulator) {
throw new CLIError(
`No simulator available with ${
args.simulator ? `name "${args.simulator}"` : `udid "${args.udid}"`
}`,
);
}
/**
* Booting simulator through `xcrun simctl boot` will boot it in the `headless` mode
* (running in the background).
*
* In order for user to see the app and the simulator itself, we have to make sure
* that the Simulator.app is running.
*
* We also pass it `-CurrentDeviceUDID` so that when we launch it for the first time,
* it will not boot the "default" device, but the one we set. If the app is already running,
* this flag has no effect.
*/
const activeDeveloperDir = child_process
.execFileSync('xcode-select', ['-p'], {encoding: 'utf8'})
.trim();
child_process.execFileSync('open', [
`${activeDeveloperDir}/Applications/Simulator.app`,
'--args',
'-CurrentDeviceUDID',
selectedSimulator.udid,
]);
if (!selectedSimulator.booted) {
bootSimulator(selectedSimulator);
}
let buildOutput, appPath;
if (!args.binaryPath) {
buildOutput = await buildProject(
xcodeProject,
selectedSimulator.udid,
scheme,
args,
);
appPath = await getBuildPath(
xcodeProject,
args.mode || args.configuration,
buildOutput,
scheme,
args.target,
);
} else {
appPath = args.binaryPath;
}
logger.info(
`Installing "${chalk.bold(appPath)} on ${selectedSimulator.name}"`,
);
child_process.spawnSync(
'xcrun',
['simctl', 'install', selectedSimulator.udid, appPath],
{stdio: 'inherit'},
);
const bundleID = child_process
.execFileSync(
'/usr/libexec/PlistBuddy',
['-c', 'Print:CFBundleIdentifier', path.join(appPath, 'Info.plist')],
{encoding: 'utf8'},
)
.trim();
logger.info(`Launching "${chalk.bold(bundleID)}"`);
const result = child_process.spawnSync('xcrun', [
'simctl',
'launch',
selectedSimulator.udid,
bundleID,
]);
if (result.status === 0) {
logger.success('Successfully launched the app on the simulator');
} else {
logger.error(
'Failed to launch the app on simulator',
result.stderr.toString(),
);
}
}
async function runOnDevice(
selectedDevice: Device,
scheme: string,
xcodeProject: IOSProjectInfo,
args: FlagsT,
) {
if (args.binaryPath && selectedDevice.type === 'catalyst') {
throw new CLIError(
'binary-path was specified for catalyst device, which is not supported.',
);
}
const isIOSDeployInstalled = child_process.spawnSync(
'ios-deploy',
['--version'],
{encoding: 'utf8'},
);
if (isIOSDeployInstalled.error) {
throw new CLIError(
`Failed to install the app on the device because we couldn't execute the "ios-deploy" command. Please install it by running "${chalk.bold(
'brew install ios-deploy',
)}" and try again.`,
);
}
if (selectedDevice.type === 'catalyst') {
const buildOutput = await buildProject(
xcodeProject,
selectedDevice.udid,
scheme,
args,
);
const appPath = await getBuildPath(
xcodeProject,
args.mode || args.configuration,
buildOutput,
scheme,
args.target,
true,
);
const appProcess = child_process.spawn(`${appPath}/${scheme}`, [], {
detached: true,
stdio: 'ignore',
});
appProcess.unref();
} else {
let buildOutput, appPath;
if (!args.binaryPath) {
buildOutput = await buildProject(
xcodeProject,
selectedDevice.udid,
scheme,
args,
);
appPath = await getBuildPath(
xcodeProject,
args.mode || args.configuration,
buildOutput,
scheme,
args.target,
);
} else {
appPath = args.binaryPath;
}
const iosDeployInstallArgs = [
'--bundle',
appPath,
'--id',
selectedDevice.udid,
'--justlaunch',
];
logger.info(`Installing and launching your app on ${selectedDevice.name}`);
const iosDeployOutput = child_process.spawnSync(
'ios-deploy',
iosDeployInstallArgs,
{encoding: 'utf8'},
);
if (iosDeployOutput.error) {
throw new CLIError(
`Failed to install the app on the device. We've encountered an error in "ios-deploy" command: ${iosDeployOutput.error.message}`,
);
}
}
return logger.success('Installed the app on the device.');
}
function bootSimulator(selectedSimulator: Device) {
const simulatorFullName = formattedDeviceName(selectedSimulator);
logger.info(`Launching ${simulatorFullName}`);
child_process.spawnSync('xcrun', ['simctl', 'boot', selectedSimulator.udid]);
}
async function getTargetPaths(
buildSettings: string,
scheme: string,
target: string | undefined,
) {
const settings = JSON.parse(buildSettings);
const targets = settings.map(
({target: settingsTarget}: any) => settingsTarget,
);
let selectedTarget = targets[0];
if (target) {
if (!targets.includes(target)) {
logger.info(
`Target ${chalk.bold(target)} not found for scheme ${chalk.bold(
scheme,
)}, automatically selected target ${chalk.bold(selectedTarget)}`,
);
} else {
selectedTarget = target;
}
}
// Find app in all building settings - look for WRAPPER_EXTENSION: 'app',
const targetIndex = targets.indexOf(selectedTarget);
const wrapperExtension =
settings[targetIndex].buildSettings.WRAPPER_EXTENSION;
if (wrapperExtension === 'app') {
return {
targetBuildDir: settings[targetIndex].buildSettings.TARGET_BUILD_DIR,
executableFolderPath:
settings[targetIndex].buildSettings.EXECUTABLE_FOLDER_PATH,
};
}
return {};
}
async function getBuildPath(
xcodeProject: IOSProjectInfo,
mode: BuildFlags['mode'],
buildOutput: string,
scheme: string,
target: string,
isCatalyst: boolean = false,
) {
const buildSettings = child_process.execFileSync(
'xcodebuild',
[
xcodeProject.isWorkspace ? '-workspace' : '-project',
xcodeProject.name,
'-scheme',
scheme,
'-sdk',
getPlatformName(buildOutput),
'-configuration',
mode,
'-showBuildSettings',
'-json',
],
{encoding: 'utf8'},
);
const {targetBuildDir, executableFolderPath} = await getTargetPaths(
buildSettings,
scheme,
target,
);
if (!targetBuildDir) {
throw new CLIError('Failed to get the target build directory.');
}
if (!executableFolderPath) {
throw new CLIError('Failed to get the app name.');
}
return `${targetBuildDir}${
isCatalyst ? '-maccatalyst' : ''
}/${executableFolderPath}`;
}
function getPlatformName(buildOutput: string) {
// Xcode can sometimes escape `=` with a backslash or put the value in quotes
const platformNameMatch = /export PLATFORM_NAME\\?="?(\w+)"?$/m.exec(
buildOutput,
);
if (!platformNameMatch) {
throw new CLIError(
'Couldn\'t find "PLATFORM_NAME" variable in xcodebuild output. Please report this issue and run your project with Xcode instead.',
);
}
return platformNameMatch[1];
}
function matchingDevice(
devices: Array<Device>,
deviceName: string | true | undefined,
) {
if (deviceName === true) {
const firstIOSDevice = devices.find((d) => d.type === 'device')!;
if (firstIOSDevice) {
logger.info(
`Using first available device named "${chalk.bold(
firstIOSDevice.name,
)}" due to lack of name supplied.`,
);
return firstIOSDevice;
} else {
logger.error('No iOS devices connected.');
return undefined;
}
}
const deviceByName = devices.find(
(device) =>
device.name === deviceName || formattedDeviceName(device) === deviceName,
);
if (!deviceByName) {
logger.error(
`Could not find a device named: "${chalk.bold(
String(deviceName),
)}". ${printFoundDevices(devices)}`,
);
}
return deviceByName;
}
function formattedDeviceName(simulator: Device) {
return simulator.version
? `${simulator.name} (${simulator.version})`
: simulator.name;
}
function printFoundDevices(devices: Array<Device>) {
return [
'Available devices:',
...devices.map((device) => ` - ${device.name} (${device.udid})`),
].join('\n');
}
export default {
name: 'run-ios',
description: 'builds your app and starts it on iOS simulator',
func: runIOS,
examples: [
{
desc: 'Run on a different simulator, e.g. iPhone SE (2nd generation)',
cmd: 'react-native run-ios --simulator "iPhone SE (2nd generation)"',
},
{
desc: "Run on a connected device, e.g. Max's iPhone",
cmd: 'react-native run-ios --device "Max\'s iPhone"',
},
{
desc: 'Run on the AppleTV simulator',
cmd:
'react-native run-ios --simulator "Apple TV" --scheme "helloworld-tvOS"',
},
],
options: [
...iosBuildOptions,
{
name: '--no-packager',
description: 'Do not launch packager while building',
},
{
name: '--binary-path <string>',
description:
'Path relative to project root where pre-built .app binary lives.',
},
{
name: '--list-devices',
description:
'List all available iOS devices and simulators and let you choose one to run the app. ',
},
{
name: '--interactive',
description:
'Explicitly select which scheme and configuration to use before running a build and select device to run the application.',
},
],
};