-
Notifications
You must be signed in to change notification settings - Fork 935
Expand file tree
/
Copy pathindex.ts
More file actions
237 lines (215 loc) · 7.38 KB
/
index.ts
File metadata and controls
237 lines (215 loc) · 7.38 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
/**
* 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} from '@react-native-community/cli-tools';
import {getAndroidProject} from '../../config/getAndroidProject';
import listAndroidDevices from './listAndroidDevices';
import tryLaunchEmulator from './tryLaunchEmulator';
import chalk from 'chalk';
import path from 'path';
import {build, runPackager, BuildFlags, options} from '../buildAndroid';
export interface Flags extends BuildFlags {
appId: string;
appIdSuffix: string;
mainActivity: string;
deviceId?: string;
listDevices?: boolean;
binaryPath?: 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) {
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.',
);
}
}
const androidProject = getAndroidProject(config);
await runPackager(args, config);
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) {
process.chdir(androidProject.sourceDir);
const cmd = process.platform.startsWith('win') ? 'gradlew.bat' : './gradlew';
const adbPath = getAdbPath();
if (args.listDevices) {
if (args.deviceId) {
logger.warn(
'Both "deviceId" 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 "list-devices" command.',
);
}
if (device.connected) {
return runOnSpecificDevice(
{...args, deviceId: device.deviceId},
adbPath,
androidProject,
);
}
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,
);
}
throw new CLIError(
`Failed to launch emulator. Reason: ${chalk.dim(result.error || '')}`,
);
}
if (args.deviceId) {
return runOnSpecificDevice(args, adbPath, androidProject);
} else {
return runOnAllDevices(args, cmd, adbPath, androidProject);
}
}
function runOnSpecificDevice(
args: Flags,
adbPath: string,
androidProject: AndroidProject,
) {
const devices = adb.getDevices(adbPath);
const {deviceId} = args;
if (devices.length > 0 && deviceId) {
if (devices.indexOf(deviceId) !== -1) {
// using '-x lint' in order to ignore linting errors while building the apk
let gradleArgs = ['build', '-x', 'lint'];
if (args.extraParams) {
gradleArgs = [...gradleArgs, ...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);
} 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,
) {
tryRunAdbReverse(args.port, selectedDevice);
tryInstallAppOnDevice(args, adbPath, selectedDevice, androidProject);
tryLaunchAppOnDevice(
selectedDevice,
androidProject.packageName,
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: '--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',
default: 'MainActivity',
},
{
name: '--deviceId <string>',
description:
'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.',
},
],
};