-
Notifications
You must be signed in to change notification settings - Fork 925
Feat: List android devices #1765
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
Changes from all commits
cd5d946
b18e35f
1f7c73a
e9068c4
c15b990
c243922
b888522
5056a05
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,125 @@ | ||
import {execSync} from 'child_process'; | ||
import adb from './adb'; | ||
import getAdbPath from './getAdbPath'; | ||
import {getEmulators} from './tryLaunchEmulator'; | ||
import os from 'os'; | ||
import prompts from 'prompts'; | ||
import chalk from 'chalk'; | ||
import {CLIError} from '@react-native-community/cli-tools'; | ||
|
||
type DeviceData = { | ||
deviceId: string | undefined; | ||
readableName: string; | ||
connected: boolean; | ||
type: 'emulator' | 'phone'; | ||
}; | ||
|
||
function toPascalCase(value: string) { | ||
return value !== '' ? value[0].toUpperCase() + value.slice(1) : value; | ||
} | ||
|
||
/** | ||
* | ||
* @param deviceId string | ||
* @returns name of Android emulator | ||
*/ | ||
function getEmulatorName(deviceId: string) { | ||
const adbPath = getAdbPath(); | ||
const buffer = execSync(`${adbPath} -s ${deviceId} emu avd name`); | ||
thymikee marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
// 1st line should get us emu name | ||
return buffer | ||
.toString() | ||
.split(os.EOL)[0] | ||
.replace(/(\r\n|\n|\r)/gm, '') | ||
.trim(); | ||
} | ||
|
||
/** | ||
* | ||
* @param deviceId string | ||
* @returns Android device name in readable format | ||
*/ | ||
function getPhoneName(deviceId: string) { | ||
const adbPath = getAdbPath(); | ||
const buffer = execSync( | ||
`${adbPath} -s ${deviceId} shell getprop | grep ro.product.model`, | ||
); | ||
return buffer | ||
.toString() | ||
.replace(/\[ro\.product\.model\]:\s*\[(.*)\]/, '$1') | ||
.trim(); | ||
Comment on lines
+48
to
+51
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. please extract transforming regex to a separate fn and write unit tests :) |
||
} | ||
|
||
async function promptForDeviceSelection( | ||
allDevices: Array<DeviceData>, | ||
): Promise<DeviceData | undefined> { | ||
if (!allDevices.length) { | ||
throw new CLIError( | ||
'No devices and/or emulators connected. Please create emulator with Android Studio or connect Android device.', | ||
); | ||
} | ||
const {device} = await prompts({ | ||
type: 'select', | ||
name: 'device', | ||
message: 'Select the device / emulator you want to use', | ||
choices: allDevices.map((d) => ({ | ||
title: `${chalk.bold(`${toPascalCase(d.type)}`)} ${chalk.green( | ||
`${d.readableName}`, | ||
)} (${d.connected ? 'connected' : 'disconnected'})`, | ||
value: d, | ||
})), | ||
min: 1, | ||
}); | ||
|
||
return device; | ||
} | ||
|
||
async function listAndroidDevices() { | ||
const adbPath = getAdbPath(); | ||
const devices = adb.getDevices(adbPath); | ||
|
||
let allDevices: Array<DeviceData> = []; | ||
|
||
devices.forEach((deviceId) => { | ||
if (deviceId.includes('emulator')) { | ||
const emulatorData: DeviceData = { | ||
deviceId, | ||
readableName: getEmulatorName(deviceId), | ||
connected: true, | ||
type: 'emulator', | ||
}; | ||
allDevices = [...allDevices, emulatorData]; | ||
} else { | ||
const phoneData: DeviceData = { | ||
deviceId, | ||
readableName: getPhoneName(deviceId), | ||
type: 'phone', | ||
connected: true, | ||
}; | ||
allDevices = [...allDevices, phoneData]; | ||
} | ||
}); | ||
|
||
const emulators = getEmulators(); | ||
|
||
// Find not booted ones: | ||
emulators.forEach((emulatorName) => { | ||
// skip those already booted | ||
if (allDevices.some((device) => device.readableName === emulatorName)) { | ||
return; | ||
} | ||
const emulatorData: DeviceData = { | ||
deviceId: undefined, | ||
readableName: emulatorName, | ||
type: 'emulator', | ||
connected: false, | ||
}; | ||
allDevices = [...allDevices, emulatorData]; | ||
}); | ||
|
||
const selectedDevice = await promptForDeviceSelection(allDevices); | ||
return selectedDevice; | ||
} | ||
|
||
export default listAndroidDevices; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,12 +1,12 @@ | ||
import os from 'os'; | ||
import execa from 'execa'; | ||
import Adb from './adb'; | ||
import adb from './adb'; | ||
|
||
const emulatorCommand = process.env.ANDROID_HOME | ||
? `${process.env.ANDROID_HOME}/emulator/emulator` | ||
: 'emulator'; | ||
|
||
const getEmulators = () => { | ||
export const getEmulators = () => { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'd consider moving it to separate file to avoid unexpected circular deps and make it clearer what's shared (although one could say |
||
try { | ||
const emulatorsOutput = execa.sync(emulatorCommand, ['-list-avds']).stdout; | ||
return emulatorsOutput.split(os.EOL).filter((name) => name !== ''); | ||
|
@@ -15,55 +15,75 @@ const getEmulators = () => { | |
} | ||
}; | ||
|
||
const launchEmulator = async (emulatorName: string, adbPath: string) => { | ||
return new Promise((resolve, reject) => { | ||
const cp = execa(emulatorCommand, [`@${emulatorName}`], { | ||
const launchEmulator = async ( | ||
emulatorName: string, | ||
adbPath: string, | ||
port?: number, | ||
): Promise<boolean> => { | ||
const manualCommand = `${emulatorCommand} @${emulatorName}`; | ||
|
||
const cp = execa( | ||
emulatorCommand, | ||
[`@${emulatorName}`, port ? '-port' : '', port ? `${port}` : ''], | ||
{ | ||
detached: true, | ||
stdio: 'ignore', | ||
}); | ||
cp.unref(); | ||
const timeout = 30; | ||
}, | ||
); | ||
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) { | ||
return new Promise<boolean>((resolve, reject) => { | ||
const bootCheckInterval = setInterval(async () => { | ||
const devices = adb.getDevices(adbPath); | ||
const connected = port | ||
? devices.find((d) => d.includes(`${port}`)) | ||
: devices.length > 0; | ||
if (connected) { | ||
cleanup(); | ||
resolve(); | ||
resolve(true); | ||
} | ||
}, 1000); | ||
|
||
// Reject command after timeout | ||
const rejectTimeout = setTimeout(() => { | ||
stopWaitingAndReject( | ||
`It took too long to start and connect with Android emulator: ${emulatorName}. You can try starting the emulator manually from the terminal with: ${manualCommand}`, | ||
); | ||
}, timeout * 1000); | ||
|
||
const cleanup = () => { | ||
clearTimeout(rejectTimeout); | ||
clearInterval(bootCheckInterval); | ||
}; | ||
|
||
cp.on('exit', () => { | ||
const stopWaitingAndReject = (message: string) => { | ||
cleanup(); | ||
reject('Emulator exited before boot.'); | ||
}); | ||
reject(new Error(message)); | ||
}; | ||
|
||
cp.on('error', (error) => { | ||
cleanup(); | ||
reject(error.message); | ||
cp.on('error', ({message}) => stopWaitingAndReject(message)); | ||
|
||
cp.on('exit', () => { | ||
stopWaitingAndReject( | ||
`The emulator (${emulatorName}) quit before it finished opening. You can try starting the emulator manually from the terminal with: ${manualCommand}`, | ||
); | ||
}); | ||
}); | ||
}; | ||
|
||
export default async function tryLaunchEmulator( | ||
adbPath: string, | ||
emulatorName?: string, | ||
port?: number, | ||
): Promise<{success: boolean; error?: string}> { | ||
const emulators = getEmulators(); | ||
if (emulators.length > 0) { | ||
try { | ||
await launchEmulator(emulators[0], adbPath); | ||
await launchEmulator(emulatorName ?? emulators[0], adbPath, port); | ||
return {success: true}; | ||
} catch (error) { | ||
return {success: false, error}; | ||
return {success: false, error: error?.message}; | ||
} | ||
} | ||
return { | ||
|
Uh oh!
There was an error while loading. Please reload this page.