Skip to content

feat: launch emulator during run-android #676

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Sep 11, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default async () => true;
Original file line number Diff line number Diff line change
Expand Up @@ -14,35 +14,35 @@ jest.mock('child_process', () => ({
}));

jest.mock('../getAdbPath');
jest.mock('../tryLaunchEmulator');
const {execFileSync} = require('child_process');

describe('--appFolder', () => {
beforeEach(() => {
jest.clearAllMocks();
});

it('uses task "install[Variant]" as default task', () => {
it('uses task "install[Variant]" as default task', async () => {
// @ts-ignore
runOnAllDevices({
await runOnAllDevices({
variant: 'debug',
});

expect(execFileSync.mock.calls[0][1]).toContain('installDebug');
});

it('uses appFolder and default variant', () => {
it('uses appFolder and default variant', async () => {
// @ts-ignore
runOnAllDevices({
await runOnAllDevices({
appFolder: 'someApp',
variant: 'debug',
});

expect(execFileSync.mock.calls[0][1]).toContain('someApp:installDebug');
});

it('uses appFolder and custom variant', () => {
it('uses appFolder and custom variant', async () => {
// @ts-ignore
runOnAllDevices({
await runOnAllDevices({
appFolder: 'anotherApp',
variant: 'staging',
});
Expand All @@ -52,19 +52,19 @@ describe('--appFolder', () => {
);
});

it('uses only task argument', () => {
it('uses only task argument', async () => {
// @ts-ignore
runOnAllDevices({
await runOnAllDevices({
tasks: ['someTask'],
variant: 'debug',
});

expect(execFileSync.mock.calls[0][1]).toContain('someTask');
});

it('uses appFolder and custom task argument', () => {
it('uses appFolder and custom task argument', async () => {
// @ts-ignore
runOnAllDevices({
await runOnAllDevices({
appFolder: 'anotherApp',
tasks: ['someTask'],
variant: 'debug',
Expand All @@ -73,9 +73,9 @@ describe('--appFolder', () => {
expect(execFileSync.mock.calls[0][1]).toContain('anotherApp:someTask');
});

it('uses multiple tasks', () => {
it('uses multiple tasks', async () => {
// @ts-ignore
runOnAllDevices({
await runOnAllDevices({
appFolder: 'app',
tasks: ['clean', 'someTask'],
});
Expand Down
2 changes: 0 additions & 2 deletions packages/platform-android/src/commands/runAndroid/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
* LICENSE file in the root directory of this source tree.
*
*/

import path from 'path';
import execa from 'execa';
import chalk from 'chalk';
Expand Down Expand Up @@ -135,7 +134,6 @@ function buildAndRun(args: Flags) {
args.appIdSuffix,
packageName,
);

const adbPath = getAdbPath();
if (args.deviceId) {
return runOnSpecificDevice(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {logger, CLIError} from '@react-native-community/cli-tools';
import adb from './adb';
import tryRunAdbReverse from './tryRunAdbReverse';
import tryLaunchAppOnDevice from './tryLaunchAppOnDevice';
import tryLaunchEmulator from './tryLaunchEmulator';
import {Flags} from '.';

function getTaskNames(
Expand All @@ -27,13 +28,30 @@ function toPascalCase(value: string) {
return value[0].toUpperCase() + value.slice(1);
}

function runOnAllDevices(
async function runOnAllDevices(
args: Flags,
cmd: string,
packageNameWithSuffix: string,
packageName: string,
adbPath: string,
) {
let devices = adb.getDevices(adbPath);
if (devices.length === 0) {
logger.info('Launching emulator...');
const result = await tryLaunchEmulator(adbPath);
if (result.success) {
logger.info('Successfully launched emulator.');
devices = adb.getDevices(adbPath);
} else {
logger.error(
`Failed to launch emulator. Reason: ${chalk.dim(result.error || '')}.`,
);
logger.warn(
'Please launch an emulator manually or connect a device. Otherwise app may fail to launch.',
);
}
}

try {
const tasks = args.tasks || ['install' + toPascalCase(args.variant)];
const gradleArgs = getTaskNames(args.appFolder, tasks);
Expand All @@ -51,7 +69,6 @@ function runOnAllDevices(
} catch (error) {
throw createInstallError(error);
}
const devices = adb.getDevices(adbPath);

(devices.length > 0 ? devices : [undefined]).forEach(
(device: string | void) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import execa from 'execa';
import Adb from './adb';

const emulatorCommand = process.env.ANDROID_HOME
? `${process.env.ANDROID_HOME}/emulator/emulator`
: 'emulator';

const getEmulators = () => {
try {
const emulatorsOutput = execa.sync(emulatorCommand, ['-list-avds']).stdout;
return emulatorsOutput.split('\n').filter(name => name !== '');
} catch {
return [];
}
};

const launchEmulator = async (emulatorName: string, adbPath: string) => {
return new Promise((resolve, reject) => {
const cp = execa(emulatorCommand, [`@${emulatorName}`], {
detached: true,
stdio: 'ignore',
});
cp.unref();
const timeout = 30;

// Reject command after timeout
const rejectTimeout = setTimeout(() => {
cleanup();
reject(`Could not start emulator within ${timeout} seconds.`);
}, timeout * 1000);

const bootCheckInterval = setInterval(() => {
if (Adb.getDevices(adbPath).length > 0) {
cleanup();
resolve();
}
}, 1000);

const cleanup = () => {
clearTimeout(rejectTimeout);
clearInterval(bootCheckInterval);
};

cp.on('exit', () => {
cleanup();
reject('Emulator exited before boot.');
});

cp.on('error', error => {
cleanup();
reject(error.message);
});
});
};

export default async function tryLaunchEmulator(
adbPath: string,
): Promise<{success: boolean; error?: string}> {
const emulators = getEmulators();
if (emulators.length > 0) {
try {
await launchEmulator(emulators[0], adbPath);
return {success: true};
} catch (error) {
return {success: false, error};
}
}
return {
success: false,
error: 'No emulators found as an output of `emulator -list-avds`',
};
}