-
Notifications
You must be signed in to change notification settings - Fork 905
/
Copy pathindex.ts
370 lines (330 loc) · 10.5 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
/**
* 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 fs from 'fs';
import {Config} from '@react-native-community/cli-types';
import adb from './adb';
import runOnAllDevices from './runOnAllDevices';
import tryRunAdbReverse from './tryRunAdbReverse';
import tryLaunchAppOnDevice from './tryLaunchAppOnDevice';
import tryInstallAppOnDevice from './tryInstallAppOnDevice';
import getAdbPath from './getAdbPath';
import {
logger,
CLIError,
link,
getDefaultUserTerminal,
startServerInNewWindow,
findDevServerPort,
} from '@react-native-community/cli-tools';
import {getAndroidProject} from '@react-native-community/cli-config-android';
import listAndroidDevices from './listAndroidDevices';
import tryLaunchEmulator from './tryLaunchEmulator';
import chalk from 'chalk';
import path from 'path';
import {build, BuildFlags, options} from '../buildAndroid';
import {promptForTaskSelection} from './listAndroidTasks';
import {getTaskNames} from './getTaskNames';
import {checkUsers, promptForUser} from './listAndroidUsers';
export interface Flags extends BuildFlags {
appId: string;
appIdSuffix: string;
mainActivity?: string;
port: number;
terminal?: string;
packager?: boolean;
device?: string;
deviceId?: string;
listDevices?: boolean;
binaryPath?: string;
user?: number | string;
}
export type AndroidProject = NonNullable<Config['project']['android']>;
/**
* Starts the app on a connected Android emulator or device.
*/
async function runAndroid(_argv: Array<string>, config: Config, args: Flags) {
link.setPlatform('android');
let {packager, port} = args;
if (packager) {
const {port: newPort, startPackager} = await findDevServerPort(
port,
config.root,
);
if (startPackager) {
// Awaiting this causes the CLI to hang indefinitely, so this must execute without await.
startServerInNewWindow(
newPort,
config.root,
config.reactNativePath,
args.terminal,
);
}
}
if (config.reactNativeVersion !== 'unknown') {
link.setVersion(config.reactNativeVersion);
}
if (args.binaryPath) {
if (args.tasks) {
throw new CLIError(
'binary-path and tasks were specified, but they are not compatible. Specify only one',
);
}
args.binaryPath = path.isAbsolute(args.binaryPath)
? args.binaryPath
: path.join(config.root, args.binaryPath);
if (args.binaryPath && !fs.existsSync(args.binaryPath)) {
throw new CLIError(
'binary-path was specified, but the file was not found.',
);
}
}
let androidProject = getAndroidProject(config);
if (args.mainActivity) {
androidProject.mainActivity = args.mainActivity;
}
return buildAndRun(args, androidProject);
}
const defaultPort = 5552;
async function getAvailableDevicePort(
port: number = defaultPort,
): Promise<number> {
/**
* The default value is 5554 for the first virtual device instance running on your machine. A virtual device normally occupies a pair of adjacent ports: a console port and an adb port. The console of the first virtual device running on a particular machine uses console port 5554 and adb port 5555. Subsequent instances use port numbers increasing by two. For example, 5556/5557, 5558/5559, and so on. The range is 5554 to 5682, allowing for 64 concurrent virtual devices.
*/
const adbPath = getAdbPath();
const devices = adb.getDevices(adbPath);
if (port > 5682) {
throw new CLIError('Failed to launch emulator...');
}
if (devices.some((d) => d.includes(port.toString()))) {
return await getAvailableDevicePort(port + 2);
}
return port;
}
// Builds the app and runs it on a connected emulator / device.
async function buildAndRun(args: Flags, androidProject: AndroidProject) {
if (args.deviceId) {
logger.warn(
'The `deviceId` parameter is renamed to `device`. Please use the new `device` argument next time to avoid this warning.',
);
args.device = args.deviceId;
}
process.chdir(androidProject.sourceDir);
const cmd = process.platform.startsWith('win') ? 'gradlew.bat' : './gradlew';
const adbPath = getAdbPath();
let selectedTask;
if (args.interactive) {
const task = await promptForTaskSelection(
'install',
androidProject.sourceDir,
);
if (task) {
selectedTask = task;
}
}
if (args.listDevices || args.interactive) {
if (args.device) {
logger.warn(
`Both ${
args.deviceId ? 'deviceId' : 'device'
} and "list-devices" parameters were passed to "run" command. We will list available devices and let you choose from one`,
);
}
const device = await listAndroidDevices();
if (!device) {
throw new CLIError(
`Failed to select device, please try to run app without ${
args.listDevices ? 'list-devices' : 'interactive'
} command.`,
);
}
if (args.interactive) {
const users = checkUsers(device.deviceId as string, adbPath);
if (users && users.length > 1) {
const user = await promptForUser(users);
if (user) {
args.user = user.id;
}
}
}
if (device.connected) {
return runOnSpecificDevice(
{...args, deviceId: device.deviceId},
adbPath,
androidProject,
selectedTask,
);
}
const port = await getAvailableDevicePort();
const emulator = `emulator-${port}`;
logger.info('Launching emulator...');
const result = await tryLaunchEmulator(adbPath, device.readableName, port);
if (result.success) {
logger.info('Successfully launched emulator.');
return runOnSpecificDevice(
{...args, deviceId: emulator},
adbPath,
androidProject,
selectedTask,
);
}
throw new CLIError(
`Failed to launch emulator. Reason: ${chalk.dim(result.error || '')}`,
);
}
if (args.device) {
return runOnSpecificDevice(args, adbPath, androidProject, selectedTask);
} else {
return runOnAllDevices(args, cmd, adbPath, androidProject);
}
}
function runOnSpecificDevice(
args: Flags,
adbPath: string,
androidProject: AndroidProject,
selectedTask?: string,
) {
const devices = adb.getDevices(adbPath);
const {deviceId} = args;
// if coming from run-android command and we have selected task
// from interactive mode we need to create appropriate build task
// eg 'installRelease' -> 'assembleRelease'
const buildTask = selectedTask
? [selectedTask.replace('install', 'assemble')]
: [];
if (devices.length > 0 && deviceId) {
if (devices.indexOf(deviceId) !== -1) {
let gradleArgs = getTaskNames(
androidProject.appName,
args.mode,
args.tasks ?? buildTask,
'install',
);
// using '-x lint' in order to ignore linting errors while building the apk
gradleArgs.push('-x', 'lint');
if (args.extraParams) {
gradleArgs.push(...args.extraParams);
}
if (args.port) {
gradleArgs.push(`-PreactNativeDevServerPort=${args.port}`);
}
if (args.activeArchOnly) {
const architecture = adb.getCPU(adbPath, deviceId);
if (architecture !== null) {
logger.info(`Detected architecture ${architecture}`);
// `reactNativeDebugArchitectures` was renamed to `reactNativeArchitectures` in 0.68.
// Can be removed when 0.67 no longer needs to be supported.
gradleArgs.push(`-PreactNativeDebugArchitectures=${architecture}`);
gradleArgs.push(`-PreactNativeArchitectures=${architecture}`);
}
}
if (!args.binaryPath) {
build(gradleArgs, androidProject.sourceDir);
}
installAndLaunchOnDevice(
args,
deviceId,
adbPath,
androidProject,
selectedTask,
);
} else {
logger.error(
`Could not find device with the id: "${deviceId}". Please choose one of the following:`,
...devices,
);
}
} else {
logger.error('No Android device or emulator connected.');
}
}
function installAndLaunchOnDevice(
args: Flags,
selectedDevice: string,
adbPath: string,
androidProject: AndroidProject,
selectedTask?: string,
) {
tryRunAdbReverse(args.port, selectedDevice);
tryInstallAppOnDevice(
args,
adbPath,
selectedDevice,
androidProject,
selectedTask,
);
tryLaunchAppOnDevice(selectedDevice, androidProject, adbPath, args);
}
export default {
name: 'run-android',
description:
'builds your app and starts it on a connected Android emulator or device',
func: runAndroid,
options: [
...options,
{
name: '--no-packager',
description: 'Do not launch packager while running the app',
},
{
name: '--port <number>',
default: process.env.RCT_METRO_PORT || 8081,
parse: Number,
},
{
name: '--terminal <string>',
description:
'Launches the Metro Bundler in a new window using the specified terminal path.',
default: getDefaultUserTerminal(),
},
{
name: '--appId <string>',
description:
'Specify an applicationId to launch after build. If not specified, `package` from AndroidManifest.xml will be used.',
default: '',
},
{
name: '--appIdSuffix <string>',
description: 'Specify an applicationIdSuffix to launch after build.',
default: '',
},
{
name: '--main-activity <string>',
description: 'Name of the activity to start',
},
{
name: '--device <string>',
description:
'Explicitly set the device to use by name. The value is not required ' +
'if you have a single device connected.',
},
{
name: '--deviceId <string>',
description:
'**DEPRECATED** Builds your app and starts it on a specific device/simulator with the ' +
'given device id (listed by running "adb devices" on the command line).',
},
{
name: '--list-devices',
description:
'Lists all available Android devices and simulators and let you choose one to run the app',
default: false,
},
{
name: '--binary-path <string>',
description:
'Path relative to project root where pre-built .apk binary lives.',
},
{
name: '--user <number>',
description: 'Id of the User Profile you want to install the app on.',
parse: Number,
},
],
};
export {adb, getAdbPath, listAndroidDevices, tryRunAdbReverse};