-
Notifications
You must be signed in to change notification settings - Fork 904
/
index.ts
540 lines (487 loc) · 13.6 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
/**
* 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, {
ChildProcess,
SpawnOptionsWithoutStdio,
} from 'child_process';
import fs from 'fs';
import path from 'path';
import chalk from 'chalk';
import {Config} from '@react-native-community/cli-types';
import findXcodeProject, {ProjectInfo} from './findXcodeProject';
import parseIOSDevicesList from './parseIOSDevicesList';
import findMatchingSimulator from './findMatchingSimulator';
import warnAboutManuallyLinkedLibs from '../../link/warnAboutManuallyLinkedLibs';
import {
logger,
CLIError,
getDefaultUserTerminal,
} from '@react-native-community/cli-tools';
import {Device} from '../../types';
type FlagsT = {
simulator: string;
configuration: string;
scheme?: string;
projectPath: string;
device?: string | true;
udid?: string;
packager: boolean;
verbose: boolean;
port: number;
terminal: string | undefined;
};
function runIOS(_: Array<string>, ctx: Config, args: FlagsT) {
if (!fs.existsSync(args.projectPath)) {
throw new CLIError(
'iOS project folder not found. Are you sure this is a React Native project?',
);
}
warnAboutManuallyLinkedLibs(ctx);
process.chdir(args.projectPath);
const xcodeProject = findXcodeProject(fs.readdirSync('.'));
if (!xcodeProject) {
throw new CLIError(
`Could not find Xcode project files in "${args.projectPath}" folder`,
);
}
const inferredSchemeName = path.basename(
xcodeProject.name,
path.extname(xcodeProject.name),
);
const scheme = args.scheme || inferredSchemeName;
logger.info(
`Found Xcode ${
xcodeProject.isWorkspace ? 'workspace' : 'project'
} "${chalk.bold(xcodeProject.name)}"`,
);
const {device, udid} = args;
if (!device && !udid) {
return runOnSimulator(xcodeProject, scheme, args);
}
const devices = parseIOSDevicesList(
// $FlowExpectedError https://github.com/facebook/flow/issues/5675
child_process.execFileSync('xcrun', ['instruments', '-s'], {
encoding: 'utf8',
}),
);
if (devices.length === 0) {
return logger.error('No iOS devices connected.');
}
const selectedDevice = matchingDevice(devices, device, udid);
if (selectedDevice) {
return runOnDevice(selectedDevice, scheme, xcodeProject, args);
}
if (device) {
return logger.error(
`Could not find a device named: "${chalk.bold(
String(device),
)}". ${printFoundDevices(devices)}`,
);
}
if (udid) {
return logger.error(
`Could not find a device with udid: "${chalk.bold(
udid,
)}". ${printFoundDevices(devices)}`,
);
}
}
async function runOnSimulator(
xcodeProject: ProjectInfo,
scheme: string,
args: FlagsT,
) {
let simulators: {devices: {[index: string]: Array<Device>}};
try {
simulators = JSON.parse(
child_process.execFileSync(
'xcrun',
['simctl', 'list', '--json', 'devices'],
{encoding: 'utf8'},
),
);
} catch (error) {
throw new CLIError('Could not parse the simulator list output', error);
}
const selectedSimulator = findMatchingSimulator(simulators, args.simulator);
if (!selectedSimulator) {
throw new CLIError(`Could not find "${args.simulator}" simulator`);
}
/**
* 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'})
// $FlowExpectedError https://github.com/facebook/flow/issues/5675
.trim();
child_process.execFileSync('open', [
`${activeDeveloperDir}/Applications/Simulator.app`,
'--args',
'-CurrentDeviceUDID',
selectedSimulator.udid,
]);
if (!selectedSimulator.booted) {
bootSimulator(selectedSimulator);
}
const appName = await buildProject(
xcodeProject,
selectedSimulator.udid,
scheme,
args,
);
const appPath = getBuildPath(args.configuration, appName, false, scheme);
logger.info(`Installing "${chalk.bold(appPath)}"`);
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'},
)
// $FlowExpectedError https://github.com/facebook/flow/issues/5675
.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);
}
}
async function runOnDevice(
selectedDevice: Device,
scheme: string,
xcodeProject: ProjectInfo,
args: FlagsT,
) {
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(
'npm install -g ios-deploy',
)}" and try again.`,
);
}
const appName = await buildProject(
xcodeProject,
selectedDevice.udid,
scheme,
args,
);
const iosDeployInstallArgs = [
'--bundle',
getBuildPath(args.configuration, appName, true, scheme),
'--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 buildProject(
xcodeProject: ProjectInfo,
udid: string | undefined,
scheme: string,
args: FlagsT,
): Promise<string> {
return new Promise((resolve, reject) => {
const xcodebuildArgs = [
xcodeProject.isWorkspace ? '-workspace' : '-project',
xcodeProject.name,
'-configuration',
args.configuration,
'-scheme',
scheme,
'-destination',
`id=${udid}`,
'-derivedDataPath',
`build/${scheme}`,
];
logger.info(
`Building ${chalk.dim(
`(using "xcodebuild ${xcodebuildArgs.join(' ')}")`,
)}`,
);
let xcpretty: ChildProcess | any;
if (!args.verbose) {
xcpretty =
xcprettyAvailable() &&
child_process.spawn('xcpretty', [], {
stdio: ['pipe', process.stdout, process.stderr],
});
}
const buildProcess = child_process.spawn(
'xcodebuild',
xcodebuildArgs,
getProcessOptions(args),
);
let buildOutput = '';
let errorOutput = '';
buildProcess.stdout.on('data', (data: Buffer) => {
const stringData = data.toString();
buildOutput += stringData;
if (xcpretty) {
xcpretty.stdin.write(data);
} else {
if (logger.isVerbose()) {
logger.debug(stringData);
} else {
process.stdout.write('.');
}
}
});
buildProcess.stderr.on('data', (data: Buffer) => {
errorOutput += data;
});
buildProcess.on('close', (code: number) => {
if (xcpretty) {
xcpretty.stdin.end();
} else {
process.stdout.write('\n');
}
if (code !== 0) {
reject(
new CLIError(
`
Failed to build iOS project.
We ran "xcodebuild" command but it exited with error code ${code}. To debug build
logs further, consider building your app with Xcode.app, by opening
${xcodeProject.name}.
`,
buildOutput + '\n' + errorOutput,
),
);
return;
}
resolve(getProductName(buildOutput) || scheme);
});
});
}
function bootSimulator(selectedSimulator: Device) {
const simulatorFullName = formattedDeviceName(selectedSimulator);
logger.info(`Launching ${simulatorFullName}`);
try {
child_process.spawnSync('xcrun', [
'instruments',
'-w',
selectedSimulator.udid,
]);
} catch (_ignored) {
// instruments always fail with 255 because it expects more arguments,
// but we want it to only launch the simulator
}
}
function getBuildPath(
configuration: string,
appName: string,
isDevice: boolean,
scheme: string,
) {
let device;
if (isDevice) {
device = 'iphoneos';
} else if (appName.toLowerCase().includes('tvos')) {
device = 'appletvsimulator';
} else {
device = 'iphonesimulator';
}
let buildPath = `build/${scheme}/Build/Products/${configuration}-${device}/${appName}.app`;
// Check wether app file exist, sometimes `-derivedDataPath` option of `xcodebuild` not works as expected.
if (!fs.existsSync(path.join(buildPath))) {
return `DerivedData/Build/Products/${configuration}-${device}/${appName}.app`;
}
return buildPath;
}
function getProductName(buildOutput: string) {
const productNameMatch = /export FULL_PRODUCT_NAME="?(.+).app"?$/m.exec(
buildOutput,
);
return productNameMatch ? productNameMatch[1] : null;
}
function xcprettyAvailable() {
try {
child_process.execSync('xcpretty --version', {
stdio: [0, 'pipe', 'ignore'],
});
} catch (error) {
return false;
}
return true;
}
function matchingDevice(
devices: Array<Device>,
deviceName: string | true | undefined,
udid: string | undefined,
) {
if (udid) {
return matchingDeviceByUdid(devices, udid);
}
if (deviceName === true && devices.length === 1) {
logger.info(
`Using first available device named "${chalk.bold(
devices[0].name,
)}" due to lack of name supplied.`,
);
return devices[0];
}
return devices.find(
device =>
device.name === deviceName || formattedDeviceName(device) === deviceName,
);
}
function matchingDeviceByUdid(
devices: Array<Device>,
udid: string | undefined,
) {
return devices.find(device => device.udid === udid);
}
function formattedDeviceName(simulator: Device) {
return `${simulator.name} (${simulator.version})`;
}
function printFoundDevices(devices: Array<Device>) {
return [
'Available devices:',
...devices.map(device => ` - ${device.name} (${device.udid})`),
].join('\n');
}
function getProcessOptions({
packager,
terminal,
port,
}: {
packager: boolean;
terminal: string | undefined;
port: number;
}): SpawnOptionsWithoutStdio {
if (packager) {
return {
env: {
...process.env,
RCT_TERMINAL: terminal,
RCT_METRO_PORT: port.toString(),
},
};
}
return {
env: {
...process.env,
RCT_TERMINAL: terminal,
RCT_NO_LAUNCH_PACKAGER: 'true',
},
};
}
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 5',
cmd: 'react-native run-ios --simulator "iPhone 5"',
},
{
desc: 'Pass a non-standard location of iOS directory',
cmd: 'react-native run-ios --project-path "./app/ios"',
},
{
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: [
{
name: '--simulator [string]',
description:
'Explicitly set simulator to use. Optionally include iOS version between' +
'parenthesis at the end to match an exact version: "iPhone 6 (10.0)"',
default: 'iPhone X',
},
{
name: '--configuration [string]',
description: 'Explicitly set the scheme configuration to use',
default: 'Debug',
},
{
name: '--scheme [string]',
description: 'Explicitly set Xcode scheme to use',
},
{
name: '--project-path [string]',
description:
'Path relative to project root where the Xcode project ' +
'(.xcodeproj) lives.',
default: 'ios',
},
{
name: '--device [string]',
description:
'Explicitly set device to use by name. The value is not required if you have a single device connected.',
},
{
name: '--udid [string]',
description: 'Explicitly set device to use by udid',
},
{
name: '--no-packager',
description: 'Do not launch packager while building',
},
{
name: '--verbose',
description: 'Do not use xcpretty even if installed',
},
{
name: '--port [number]',
default: process.env.RCT_METRO_PORT || 8081,
parse: (val: string) => Number(val),
},
{
name: '--terminal [string]',
description:
'Launches the Metro Bundler in a new window using the specified terminal path.',
default: getDefaultUserTerminal,
},
],
};