# All files / src/platformTools/apple deviceManager.js

12.96% Statements 21/162
0% Branches 0/100
0% Functions 0/22
15.96% Lines 15/94

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    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
    1622x
    2x
    2x
    2x

    2x
    2x
    2x

    2x

    2x

    2x

    2x

    2x

    2x

    2x

    2x

     import inquirer from 'inquirer';
    import chalk from 'chalk';
    import child_process from 'child_process';
    import {
        getAppFolder,
        isPlatformActive,
    } from '../../common';
    import { logToSummary, logTask, logWarning, logDebug } from '../../systemTools/logger';
    import { IOS, TVOS } from '../../constants';
    import { executeAsync } from '../../systemTools/exec';

    export const getAppleDevices = async (c, platform, ignoreDevices, ignoreSimulators) => {
        logTask(`getAppleDevices:${platform},ignoreDevices:${ignoreDevices},ignoreSimulators${ignoreSimulators}`);
        const { program: { skipTargetCheck } } = c;
        // const devices = child_process.execFileSync('xcrun', ['instruments', '-s'], {
        //     encoding: 'utf8',
        // });

        const devicesAndSims = await executeAsync('xcrun instruments -s');
        const simctl = JSON.parse(await executeAsync('xcrun simctl list --json'));
        const availableSims = [];
        Object.keys(simctl.devices).forEach((runtime) => {
            console.log('runtime', runtime);
            simctl.devices[runtime].forEach((device) => {
                if (device.isAvailable) availableSims.push({ ...device, version: runtime.split('.').pop() });
            });
        });

        const devicesArr = _parseIOSDevicesList(devicesAndSims, platform, ignoreDevices, ignoreSimulators);
        const simulatorsArr = _parseIOSDevicesList(availableSims, platform, ignoreDevices, ignoreSimulators);
        let allDevices = [...devicesArr, ...simulatorsArr];

        if (!skipTargetCheck) {
            // filter watches
            allDevices = allDevices.filter(d => !d.version.includes('watchOS'));
            // filter other platforms
            allDevices = allDevices.filter((d) => {
                if (platform === IOS && (d.icon?.includes('Phone') || d.icon?.includes('Tablet'))) return true;
                if (platform === TVOS && d.icon?.includes('TV')) return true;
                return false;
            });
        }
        return allDevices;
    };

    const _parseIOSDevicesList = (rawDevices, platform, ignoreDevices = false, ignoreSimulators = false) => {
        const devices = [];
        const decideIcon = (device) => {
            const { name, isDevice } = device;
            switch (platform) {
            case IOS:
                if (name.includes('iPhone') || name.includes('iPad') || name.includes('iPod') || isDevice) {
                    let icon = 'Phone 📱';
                    if (name.includes('iPad')) icon = 'Tablet 💊';
                    return icon;
                }
                return null;
            case TVOS:
                if ((name.includes('Apple TV') || isDevice) && !name.includes('iPhone') && !name.includes('iPad')) {
                    return 'TV 📺';
                }
                return null;
            default:
                return null;
            }
        };
        if (typeof rawDevices === 'string' && !ignoreDevices) {
            rawDevices.split('\n').forEach((line) => {
                const s1 = line.match(/\[.*?\]/);
                const s2 = line.match(/\(.*?\)/g);
                const s3 = line.substring(0, line.indexOf('(') - 1);
                const s4 = line.substring(0, line.indexOf('[') - 1);
                let isSim = false;
                if (s2 && s1) {
                    if (s2[s2.length - 1] === '(Simulator)') {
                        isSim = true;
                        s2.pop();
                    }
                    const version = s2.pop();
                    let name = `${s4.substring(0, s4.lastIndexOf('(') - 1)}`;
                    name = name || 'undefined';
                    const udid = s1[0].replace(/\[|\]/g, '');
                    const isDevice = !isSim;
                    if (!isDevice) return; // only take care of devices.

                    if (!ignoreDevices) {
                        const device = { udid, name, version, isDevice };
                        devices.push({ ...device, icon: decideIcon(device) });
                    }
                }
            });
        } else if (typeof rawDevices === 'object' && !ignoreSimulators) {
            rawDevices.forEach((d) => {
                const { name, udid, version } = d;
                const device = {
                    name,
                    udid,
                    isDevice: false,
                    version
                };
                devices.push({ ...device, icon: decideIcon(device) });
            });
        }

        return devices;
    };

    export const launchAppleSimulator = async (c, platform, target) => {
        logTask(`launchAppleSimulator:${platform}:${target}`);

        const devicesArr = await getAppleDevices(c, platform, true);
        let selectedDevice;
        for (let i = 0; i < devicesArr.length; i++) {
            if (devicesArr[i].name === target) {
                selectedDevice = devicesArr[i];
            }
        }
        if (selectedDevice) {
            _launchSimulator(selectedDevice);
            return selectedDevice.name;
        }

        logWarning(`Your specified simulator target ${chalk.white(target)} doesn't exists`);
        const devices = devicesArr.map(v => ({ name: `${v.name} | ${v.icon} | v: ${chalk.green(v.version)} | udid: ${chalk.grey(v.udid)}${v.isDevice ? chalk.red(' (device)') : ''}`, value: v }));

        const { sim } = await inquirer.prompt({
            name: 'sim',
            message: 'Select the simulator you want to launch',
            type: 'list',
            choices: devices
        });

        if (sim) {
            _launchSimulator(sim);
            return sim.name;
        }
        return Promise.reject('Action canceled!');
    };

    const _launchSimulator = (selectedDevice) => {
        try {
            child_process.spawnSync('xcrun', ['instruments', '-w', selectedDevice.udid]);
        } catch (e) {
            // instruments always fail with 255 because it expects more arguments,
            // but we want it to only launch the simulator
        }
    };

    export const listAppleDevices = async (c, platform) => {
        logTask(`listAppleDevices:${platform}`);

        const devicesArr = await getAppleDevices(c, platform);
        let devicesString = '';
        devicesArr.forEach((v, i) => {
            devicesString += ` [${i + 1}]> ${chalk.bold(v.name)} | ${v.icon} | v: ${chalk.green(v.version)} | udid: ${chalk.grey(v.udid)}${
                v.isDevice ? chalk.red(' (device)') : ''
            }\n`;
        });

        logToSummary(`${platform} Targets:\n\n${devicesString}`);
    };