import { CliParameters } from './cli-parameters' ; import { ErrorCode , createError } from './errors' ; import { which } from './which' ; import * as execa from 'execa' ; import { existsSync , createWriteStream } from 'fs' ; /**
 * Finds the path to adb or throws an error.
 */ export function getAdbPath ( ) { const androidHome = process . env [ 'ANDROID_HOME' ] ; if ( ! androidHome ) { throw createError ( ErrorCode . MissingAndroidHome ) ; } const adb = `${ androidHome }/platform-tools/adb` ; if ( ! existsSync ( adb ) ) { throw createError ( ErrorCode . MissingAndroidAdb ) ; } return adb ; } /**
 * Finds the path to perl or throws an error.
 */ export async function getPerlPath ( ) { try { return await which ( 'perl' ) ; } catch ( err ) { throw createError ( ErrorCode . MissingPerl ) ; } } param adb param device export async function checkEmulator ( adb , device ? ) { const response = await execa ( adb , [ 'devices' ] ) ; const stdout = response . stdout as string ; const devices = stdout . split ( '\n' ) . filter ( line => line . endsWith ( '\tdevice' ) ) . map ( line => line . replace ( '\tdevice' , '' ) ) ; if ( devices . length === 0 ) { throw createError ( ErrorCode . NoRunningAndroidEmulators ) ; } if ( devices . length === 1 && ! device ) { return devices [ 0 ] ; } if ( devices . length > 1 && ! device ) { throw createError ( ErrorCode . AmbiguousAndroidEmulator ) ; } if ( devices . indexOf ( device ) < 0 ) { throw createError ( ErrorCode . MissingAndroidEmulator ) ; } } param adb param device param filename export async function saveScreenshot ( adb , perl , device , filename ) { return new Promise ( ( resolve , reject ) => { try { const maxBuffer = 1024 * 1000 * 50 ; const adbProcess = execa ( adb , [ '-s' , device , 'exec-out' , 'screencap' , '-p' ] , { maxBuffer } ) ; adbProcess . stdout . pipe ( createWriteStream ( filename ) ) ; adbProcess . on ( 'exit' , exitCode => { if ( exitCode === 0 ) { resolve ( ) ; } else { reject ( ) ; } } ) ; } catch ( err ) { throw createError ( ErrorCode . ScreenshotFail ) ; } } ) ; } param parameters export async function saveToFile ( parameters ) { const adb = getAdbPath ( ) ; const perl = await getPerlPath ( ) ; const device = await checkEmulator ( adb , parameters . device ) ; await saveScreenshot ( adb , perl , device , parameters . filename ) ; }