forked from facebook/react-native
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrunAndroid.js
More file actions
485 lines (452 loc) · 12.8 KB
/
runAndroid.js
File metadata and controls
485 lines (452 loc) · 12.8 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
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
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const adb = require('./adb');
const chalk = require('chalk');
const child_process = require('child_process');
const fs = require('fs');
const isPackagerRunning = require('../util/isPackagerRunning');
const findReactNativeScripts = require('../util/findReactNativeScripts');
const isString = require('lodash/isString');
const path = require('path');
const Promise = require('promise');
// Verifies this is an Android project
function checkAndroid(root) {
return fs.existsSync(path.join(root, 'android/gradlew'));
}
/**
* Starts the app on a connected Android emulator or device.
*/
function runAndroid(argv, config, args) {
if (!checkAndroid(args.root)) {
const reactNativeScriptsPath = findReactNativeScripts();
if (reactNativeScriptsPath) {
child_process.spawnSync(
reactNativeScriptsPath,
['android'].concat(process.argv.slice(1)),
{stdio: 'inherit'},
);
} else {
console.log(
chalk.red(
'Android project not found. Maybe run react-native android first?',
),
);
}
return;
}
if (!args.packager) {
return buildAndRun(args);
}
return isPackagerRunning(args.port).then(result => {
if (result === 'running') {
console.log(chalk.bold('JS server already running.'));
} else if (result === 'unrecognized') {
console.warn(
chalk.yellow('JS server not recognized, continuing with build...'),
);
} else {
// result == 'not_running'
console.log(chalk.bold('Starting JS server...'));
startServerInNewWindow(args.port, args.terminal);
}
return buildAndRun(args);
});
}
function getAdbPath() {
return process.env.ANDROID_HOME
? process.env.ANDROID_HOME + '/platform-tools/adb'
: 'adb';
}
// Runs ADB reverse tcp:8081 tcp:8081 to allow loading the jsbundle from the packager
function tryRunAdbReverse(packagerPort, device) {
try {
const adbPath = getAdbPath();
const adbArgs = ['reverse', `tcp:${packagerPort}`, `tcp:${packagerPort}`];
// If a device is specified then tell adb to use it
if (device) {
adbArgs.unshift('-s', device);
}
console.log(chalk.bold(`Running ${adbPath} ${adbArgs.join(' ')}`));
child_process.execFileSync(adbPath, adbArgs, {
stdio: [process.stdin, process.stdout, process.stderr],
});
} catch (e) {
console.log(chalk.yellow(`Could not run adb reverse: ${e.message}`));
}
}
function getPackageNameWithSuffix(appId, appIdSuffix, packageName) {
if (appId) {
return appId;
} else if (appIdSuffix) {
return packageName + '.' + appIdSuffix;
}
return packageName;
}
// Builds the app and runs it on a connected emulator / device.
function buildAndRun(args) {
process.chdir(path.join(args.root, 'android'));
const cmd = process.platform.startsWith('win') ? 'gradlew.bat' : './gradlew';
const packageName = fs
.readFileSync(`${args.appFolder}/src/main/AndroidManifest.xml`, 'utf8')
.match(/package="(.+?)"/)[1];
const packageNameWithSuffix = getPackageNameWithSuffix(
args.appId,
args.appIdSuffix,
packageName,
);
const adbPath = getAdbPath();
if (args.deviceId) {
if (isString(args.deviceId)) {
runOnSpecificDevice(
args,
cmd,
packageNameWithSuffix,
packageName,
adbPath,
);
} else {
console.log(chalk.red('Argument missing for parameter --deviceId'));
}
} else {
runOnAllDevices(args, cmd, packageNameWithSuffix, packageName, adbPath);
}
}
function runOnSpecificDevice(
args,
gradlew,
packageNameWithSuffix,
packageName,
adbPath,
) {
let devices = adb.getDevices();
if (devices && devices.length > 0) {
if (devices.indexOf(args.deviceId) !== -1) {
buildApk(gradlew);
installAndLaunchOnDevice(
args,
args.deviceId,
packageNameWithSuffix,
packageName,
adbPath,
);
} else {
console.log(
'Could not find device with the id: "' + args.deviceId + '".',
);
console.log('Choose one of the following:');
console.log(devices);
}
} else {
console.log('No Android devices connected.');
}
}
function buildApk(gradlew) {
try {
console.log(chalk.bold('Building the app...'));
// using '-x lint' in order to ignore linting errors while building the apk
child_process.execFileSync(gradlew, ['build', '-x', 'lint'], {
stdio: [process.stdin, process.stdout, process.stderr],
});
} catch (e) {
console.log(
chalk.red('Could not build the app, read the error above for details.\n'),
);
}
}
function tryInstallAppOnDevice(args, device) {
try {
const pathToApk = `${args.appFolder}/build/outputs/apk/${
args.appFolder
}-debug.apk`;
const adbPath = getAdbPath();
const adbArgs = ['-s', device, 'install', pathToApk];
console.log(
chalk.bold(
`Installing the app on the device (cd android && adb -s ${device} install ${pathToApk}`,
),
);
child_process.execFileSync(adbPath, adbArgs, {
stdio: [process.stdin, process.stdout, process.stderr],
});
} catch (e) {
console.log(e.message);
console.log(
chalk.red(
'Could not install the app on the device, read the error above for details.\n',
),
);
}
}
function tryLaunchAppOnDevice(
device,
packageNameWithSuffix,
packageName,
adbPath,
mainActivity,
) {
try {
const adbArgs = [
'-s',
device,
'shell',
'am',
'start',
'-n',
packageNameWithSuffix + '/' + packageName + '.' + mainActivity,
];
console.log(
chalk.bold(
`Starting the app on ${device} (${adbPath} ${adbArgs.join(' ')})...`,
),
);
child_process.spawnSync(adbPath, adbArgs, {stdio: 'inherit'});
} catch (e) {
console.log(
chalk.red('adb invocation failed. Do you have adb in your PATH?'),
);
}
}
function installAndLaunchOnDevice(
args,
selectedDevice,
packageNameWithSuffix,
packageName,
adbPath,
) {
tryRunAdbReverse(args.port, selectedDevice);
tryInstallAppOnDevice(args, selectedDevice);
tryLaunchAppOnDevice(
selectedDevice,
packageNameWithSuffix,
packageName,
adbPath,
args.mainActivity,
);
}
function runOnAllDevices(
args,
cmd,
packageNameWithSuffix,
packageName,
adbPath,
) {
try {
const gradleArgs = [];
if (args.variant) {
gradleArgs.push(
'install' + args.variant[0].toUpperCase() + args.variant.slice(1),
);
} else if (args.flavor) {
console.warn(
chalk.yellow('--flavor has been deprecated. Use --variant instead'),
);
gradleArgs.push(
'install' + args.flavor[0].toUpperCase() + args.flavor.slice(1),
);
} else {
gradleArgs.push('installDebug');
}
if (args.installDebug) {
gradleArgs.push(args.installDebug);
}
console.log(
chalk.bold(
`Building and installing the app on the device (cd android && ${cmd} ${gradleArgs.join(
' ',
)})...`,
),
);
child_process.execFileSync(cmd, gradleArgs, {
stdio: [process.stdin, process.stdout, process.stderr],
});
} catch (e) {
console.log(
chalk.red(
'Could not install the app on the device, read the error above for details.\n' +
'Make sure you have an Android emulator running or a device connected and have\n' +
'set up your Android development environment:\n' +
'https://facebook.github.io/react-native/docs/getting-started.html',
),
);
// stderr is automatically piped from the gradle process, so the user
// should see the error already, there is no need to do
// `console.log(e.stderr)`
return Promise.reject();
}
const devices = adb.getDevices();
if (devices && devices.length > 0) {
devices.forEach(device => {
tryRunAdbReverse(args.port, device);
tryLaunchAppOnDevice(
device,
packageNameWithSuffix,
packageName,
adbPath,
args.mainActivity,
);
});
} else {
try {
// If we cannot execute based on adb devices output, fall back to
// shell am start
const fallbackAdbArgs = [
'shell',
'am',
'start',
'-n',
packageNameWithSuffix + '/' + packageName + '.MainActivity',
];
console.log(
chalk.bold(
`Starting the app (${adbPath} ${fallbackAdbArgs.join(' ')}...`,
),
);
child_process.spawnSync(adbPath, fallbackAdbArgs, {stdio: 'inherit'});
} catch (e) {
console.log(
chalk.red('adb invocation failed. Do you have adb in your PATH?'),
);
// stderr is automatically piped from the gradle process, so the user
// should see the error already, there is no need to do
// `console.log(e.stderr)`
return Promise.reject();
}
}
}
function startServerInNewWindow(port, terminal = process.env.REACT_TERMINAL) {
// set up OS-specific filenames and commands
const isWindows = /^win/.test(process.platform);
const scriptFile = isWindows
? 'launchPackager.bat'
: 'launchPackager.command';
const packagerEnvFilename = isWindows ? '.packager.bat' : '.packager.env';
const portExportContent = isWindows
? `set RCT_METRO_PORT=${port}`
: `export RCT_METRO_PORT=${port}`;
// set up the launchpackager.(command|bat) file
const scriptsDir = path.resolve(__dirname, '..', '..', 'scripts');
const launchPackagerScript = path.resolve(scriptsDir, scriptFile);
const procConfig = {cwd: scriptsDir};
// set up the .packager.(env|bat) file to ensure the packager starts on the right port
const packagerEnvFile = path.join(
__dirname,
'..',
'..',
'scripts',
packagerEnvFilename,
);
// ensure we overwrite file by passing the 'w' flag
fs.writeFileSync(packagerEnvFile, portExportContent, {
encoding: 'utf8',
flag: 'w',
});
if (process.platform === 'darwin') {
if (terminal) {
return child_process.spawnSync(
'open',
['-a', terminal, launchPackagerScript],
procConfig,
);
}
return child_process.spawnSync('open', [launchPackagerScript], procConfig);
} else if (process.platform === 'linux') {
if (terminal) {
procConfig.detached = true;
return child_process.spawn(
terminal,
['-e', 'sh ' + launchPackagerScript],
procConfig,
);
}
// By default, the child shell process will be attached to the parent
procConfig.detached = false;
return child_process.spawn('sh', [launchPackagerScript], procConfig);
} else if (/^win/.test(process.platform)) {
procConfig.detached = true;
procConfig.stdio = 'ignore';
return child_process.spawn(
'cmd.exe',
['/C', launchPackagerScript],
procConfig,
);
} else {
console.log(
chalk.red(
`Cannot start the packager. Unknown platform ${process.platform}`,
),
);
}
}
module.exports = {
name: 'run-android',
description:
'builds your app and starts it on a connected Android emulator or device',
func: runAndroid,
options: [
{
command: '--install-debug',
},
{
command: '--root [string]',
description:
'Override the root directory for the android build (which contains the android directory)',
default: '',
},
{
command: '--flavor [string]',
description: '--flavor has been deprecated. Use --variant instead',
},
{
command: '--variant [string]',
},
{
command: '--appFolder [string]',
description:
'Specify a different application folder name for the android source.',
default: 'app',
},
{
command: '--appId [string]',
description: 'Specify an applicationId to launch after build.',
default: '',
},
{
command: '--appIdSuffix [string]',
description: 'Specify an applicationIdSuffix to launch after build.',
default: '',
},
{
command: '--main-activity [string]',
description: 'Name of the activity to start',
default: 'MainActivity',
},
{
command: '--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).',
},
{
command: '--no-packager',
description: 'Do not launch packager while building',
},
{
command: '--port [number]',
default: process.env.RCT_METRO_PORT || 8081,
parse: (val: string) => Number(val),
},
{
command: '--terminal [string]',
description:
'Launches the Metro Bundler in a new window using the specified terminal path.',
default: '',
},
],
};