All files / wdio-cli/src utils.js

100% Statements 65/65
97.37% Branches 37/38
100% Functions 22/22
100% Lines 59/59

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 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      3x           5x 5x 3x 2x       1x                     5x   5x 1x     5x 6x 6x   1x                           7x 1x     7x 10x 10x 8x   2x 2x                       5x 4x     4x       3x               20x             20x 14x     20x             1x   1x 3x     1x       1x       5x   1x     2x         1x       4x   4x 2x     4x   4x               2x 2x 2x 1x   1x   1x                 5x 2x 2x   1x                       5x 3x 3x 1x 2x   1x                  
import logger from '@wdio/logger'
import { execSync } from 'child_process'
 
const log = logger('@wdio/cli:utils')
 
/**
 * run service launch sequences
 */
export async function runServiceHook (launcher, hookName, ...args) {
    try {
        return await Promise.all(launcher.map((service) => {
            if (typeof service[hookName] === 'function') {
                return service[hookName](...args)
            }
        }))
    } catch (e) {
        log.error(`A service failed in the '${hookName}' hook\n${e.stack}\n\nContinue...`)
    }
}
 
/**
 * Run onPrepareHook in Launcher
 * @param {Array|Function} onPrepareHook - can be array of functions or single function
 * @param {Object} config
 * @param {Object} capabilities
 */
export async function runOnPrepareHook(onPrepareHook, config, capabilities) {
    const catchFn = (e) => log.error(`Error in onPrepareHook: ${e.stack}`)
 
    if (typeof onPrepareHook === 'function') {
        onPrepareHook = [onPrepareHook]
    }
 
    return Promise.all(onPrepareHook.map((hook) => {
        try {
            return hook(config, capabilities)
        } catch (e) {
            return catchFn(e)
        }
    })).catch(catchFn)
}
 
/**
 * Run onCompleteHook in Launcher
 * @param {Array|Function} onCompleteHook - can be array of functions or single function
 * @param {*} config
 * @param {*} capabilities
 * @param {*} exitCode
 * @param {*} results
 */
export async function runOnCompleteHook(onCompleteHook, config, capabilities, exitCode, results) {
    if (typeof onCompleteHook === 'function') {
        onCompleteHook = [onCompleteHook]
    }
 
    return Promise.all(onCompleteHook.map(async (hook) => {
        try {
            await hook(exitCode, config, capabilities, results)
            return 0
        } catch (e) {
            log.error(`Error in onCompleteHook: ${e.stack}`)
            return 1
        }
    }))
}
 
/**
 * map package names
 * used in the CLI to find the name of the package for different questions
 * answers.framework {String}
 * answers.reporters | answer.services {Array<string>}
 */
export function getNpmPackageName(pkgLabels) {
    if (typeof pkgLabels === 'string') {
        return pkgLabels.split('/package/')[1]
    }
 
    return pkgLabels.map(pkgLabel => pkgLabel.split('/package/')[1])
}
 
export function getPackageName(pkg) {
    return pkg.trim().split(' -')[0]
}
 
/**
 * get runner identification by caps
 */
export function getRunnerName (caps = {}) {
    let runner =
        caps.browserName ||
        caps.appPackage ||
        caps.appWaitActivity ||
        caps.app ||
        caps.platformName
 
    // MultiRemote
    if (!runner) {
        runner = Object.values(caps).length === 0 || Object.values(caps).some(cap => !cap.capabilities) ? 'undefined' : 'MultiRemote'
    }
 
    return runner
}
 
/**
 * used by the install command to better find the package to install
 */
export function parseInstallNameAndPackage(list) {
    const returnObj = {}
 
    for(let item of list) {
        returnObj[getPackageName(item)] = getNpmPackageName(item)
    }
 
    return returnObj
}
 
function buildNewConfigArray(str, type, change) {
    const newStr = str
        .split(`${type}s: `)[1]
        .replace('\'', '')
 
    let newArray = newStr.match(/(\w*)/gmi).filter(e => !!e).concat([change])
 
    return str
        .replace('// ', '')
        .replace(
            new RegExp(`(${type}s: )((.*\\s*)*)`), `$1[${newArray.map(e => `'${e}'`)}]`
        )
}
 
function buildNewConfigString(str, type, change) {
    return str.replace(new RegExp(`(${type}: )('\\w*')`), `$1'${change}'`)
}
 
export function findInConfig(config, type) {
    let regexStr = `[\\/\\/]*[\\s]*${type}s: [\\s]*\\[([\\s]*['|"]\\w*['|"],*)*[\\s]*\\]`
 
    if (type === 'framework') {
        regexStr = `[\\/\\/]*[\\s]*${type}: ([\\s]*['|"]\\w*['|"])`
    }
 
    const regex = new RegExp(regexStr, 'gmi')
 
    return config.match(regex)
}
 
export function replaceConfig(
    config,
    type,
    name
) {
    const match = findInConfig(config, type)
    Eif (match && match.length) {
        if (type === 'framework') {
            return buildNewConfigString(config, type, name)
        }
        const text = match.pop()
 
        return config.replace(text, buildNewConfigArray(text, type, name))
    }
}
 
export function addServiceDeps(names, packages, update) {
    /**
     * automatically install latest Chromedriver if `wdio-chromedriver-service`
     * was selected for install
     */
    if (names.some((answer) => answer.includes('wdio-chromedriver-service'))) {
        packages.push('chromedriver')
        if (update) {
            // eslint-disable-next-line no-console
            console.log(
                '\n=======',
                '\nPlease change path to / in your wdio.conf.js:',
                "\npath: '/'",
                '\n=======\n')
        }
    }
 
    /**
     * install Appium if it is not installed globally if `@wdio/appium-service`
     * was selected for install
     */
    if (names.some((answer) => answer.includes('@wdio/appium-service'))) {
        const result = execSync('appium --version || echo APPIUM_MISSING').toString().trim()
        if (result === 'APPIUM_MISSING') {
            packages.push('appium')
        } else if (update) {
            // eslint-disable-next-line no-console
            console.log(
                '\n=======',
                '\nUsing globally installed appium', result,
                '\nPlease add the following to your wdio.conf.js:',
                "\nappium: { command: 'appium' }",
                '\n=======\n')
        }
    }
}