All files / src/systemTools exec.js

73.58% Statements 142/193
60.38% Branches 64/106
69.44% Functions 25/36
70.97% Lines 110/155

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 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 3204x 4x 4x 4x 4x 4x 4x 4x   25x                                         4x 4x               4x   4x   4x 4x   4x   4x 4x 4x 1x 1x     4x 4x 4x   4x             4x   4x   4x 3x 3x 3x 3x     4x   4x 4x     4x 3x 3x 3x 3x   3x   1x 1x 1x 1x   1x       1x                             4x 1x   1x 1x 1x           4x                     4x 4x 4x 4x                     4x 1x 1x   1x   1x       1x         1x 4x   4x   4x 1x   1x       4x 1x 1x     1x       4x             4x                 4x 1x 1x 1x       1x   1x             4x                             4x 1x 1x 1x     1x               4x                       4x 3x         3x     4x                       4x 2x 2x 1x 1x 1x 1x             1x     1x   4x   4x 1x 1x     1x 4x   4x       4x       4x    
/* eslint-disable import/no-cycle */
import path from 'path';
import fs, { access, accessSync, constants } from 'fs';
import chalk from 'chalk';
import execa from 'execa';
import ora from 'ora';
import NClient from 'netcat/client';
import util from 'util';
 
import { logDebug, parseErrorMessage } from '../common';EEE
 
const { exec, execSync } = require('child_process');
 
/**
 *
 * Also accepts the Node's child_process exec/spawn options
 *
 * @typedef {Object} Opts
 * @property {Object} privateParams - private params that will be masked in the logs
 * @property {Boolean} silent - don't print anything
 * @property {Boolean} ignoreErrors - will print the loader but it will finish with a
 * checkmark regardless of the outcome. Also, it never throws a catch.
 *
 * Execute commands
 *
 * @param {String} command - command to be executed
 * @param {Opts} [opts={}] - the options for the command
 * @returns {Promise}
 *
 */
const _execute = (c, command, opts = {}) => {
    const defaultOpts = {
        stdio: 'pipe',
        localDir: path.resolve('./node_modules/.bin'),
        preferLocal: true,
        all: true,
        maxErrorLength: c.program?.maxErrorLength,
        mono: c.program?.mono,
    };
    const mergedOpts = { ...defaultOpts, ...opts };
 
    let cleanCommand = command;
    let interval;
    const intervalTimer = 30000; // 30s
    let timer = intervalTimer;
 
    if (Array.isArray(command)) cleanCommand = command.join(' ');
 
    let logMessage = cleanCommand;
    const { privateParams } = mergedOpts;
    if (privateParams && Array.isArray(privateParams)) {
        logMessage = util.format(command, Array.from(privateParams, () => '*******'));
        cleanCommand = util.format(command, ...privateParams);
    }
 
    logDebug(`_execute: ${logMessage}`);
    const { silent, mono, maxErrorLength, ignoreErrors } = mergedOpts;
    const spinner = !silent && !mono && ora({ text: `Executing: ${logMessage}` }).start();
 
  I  if (mono) {
        interval = setInterval(() => {
            console.log(`Executing: ${logMessage} - ${timer / 1000}s`);
            timer += intervalTimer;
        }, intervalTimer);
    }
 
    const child = execa.command(cleanCommand, mergedOpts);
 
    const MAX_OUTPUT_LENGTH = 200;
 
    const printLastLine = (buffer) => {
        const text = Buffer.from(buffer).toString().trim();
        const lastLine = text.split('\n').pop();
        spinner.text = lastLine.substring(0, MAX_OUTPUT_LENGTH);
    I    if (lastLine.length === MAX_OUTPUT_LENGTH) spinner.text += '...';
    };
 
  I  if (c.program?.info) {
        child.stdout.pipe(process.stdout);
    } elsEe if (spinner) {
        child.stdout.on('data', printLastLine);
    }
 
    return child.then((res) => {
        spinner && child.stdout.off('data', printLastLine);
        !silent && !mono && spinner.succeed(`Executing: ${logMessage}`);
        logDebug(res.all);
        interval && clearInterval(interval);
        // logDebug(res);
        return res.stdout;
    }).catch((err) => {
        spinner && child.stdout.off('data', printLastLine);
    E    if (!silent && !mono && !ignoreErrors) spinner.fail(parseErrorMessage(err.all, maxErrorLength) || err.stderr || err.message); // parseErrorMessage will return false if nothing is found, default to previous implementation
        logDebug(err.all);
        interval && clearInterval(interval);
        // logDebug(err);
    I    if (ignoreErrors && !silent && !mono) {
            spinner.succeed(`Executing: ${logMessage}`);
            return true;
        }
        return Promise.reject(parseErrorMessage(err.all, maxErrorLength) || err.stderr || err.message); // parseErrorMessage will return false if nothing is found, default to previous implementation
    });
};
 
/**
 *
 * Execute CLI command
 *
 * @param {Object} c - the trusty old c object
 * @param {String} cli - the cli to be executed
 * @param {String} command - the command to be executed
 * @param {Opts} [opts={}] - the options for the command
 * @returns {Promise}
 *
 */
const execCLI = (c, cli, command, opts = {}) => {
    const p = c.cli[cli];
 
  E  if (!fs.existsSync(p)) {
        logDebug('execCLI error', cli, command);
        return Promise.reject(`Location of your cli ${chalk.white(p)} does not exists. check your ${chalk.white(
            c.paths.globalConfigPath
        )} file if you SDK path is correct`);
    }
 
    return _execute(c, `${p} ${command}`, { ...opts, shell: true });
};
 
/**
 *
 * Execute a plain command
 *
 * @param {String} command - the command to be executed
 * @param {Opts} [opts={}] - the options for the command
 * @returns {Promise}
 *
 */
const executeAsync = (c, cmd, opts) => {
  I  if (cmd.includes('npm') && process.platform === 'win32') cmd.replace('npm', 'npm.cmd');
    return _execute(c, cmd, opts);
};
 
/**
 *
 * Connect to a local telnet server and execute a command
 *
 * @param {Number|String} port - where do you want me to connect to?
 * @param {String} command - the command to be executed once I'm connected
 * @returns {Promise}
 *
 */
const executeTelnet = (port, command) => new Promise((resolve) => {
    const nc2 = new NClient();
    logDebug(`execTelnet: ${port} ${command}`);
 
    let output = '';
 
    nc2.addr('127.0.0.1')
        .port(parseInt(port, 10))
        .connect()
        .send(`${command}\n`);
    nc2.on('data', (data) => {
        const resp = Buffer.from(data).toString();
        output += resp;
        if (output.includes('OK')) nc2.close();
    });
    nc2.on('close', () => resolve(output));
});
 
const isUsingWindows = process.platform === 'win32';
 
const fileNotExists = (commandName, callback) => {
    access(commandName, constants.F_OK,
        (err) => {
            callback(!err);
        });
};
 
const fileNotExistsSync = (commandName) => {
    try {
        accessSync(commandName, constants.F_OK);
        return false;
    } catch (e) {
        return true;
    }
};
 
const localExecutable = (commandName, callback) => {
    access(commandName, constants.F_OK | constants.X_OK,
        (err) => {
            callback(null, !err);
        });
};
 
const localExecutableSync = (commandName) => {
    try {
        accessSync(commandName, constants.F_OK | constants.X_OK);
        return true;
    } catch (e) {
        return false;
    }
};
 
const commandExistsUnix = (commandName, cleanedCommandName, callback) => {
    fileNotExists(commandName, (isFile) => {
    E    if (!isFile) {
            exec(`command -v ${cleanedCommandName
            } 2>/dev/null`
                  + ` && { echo >&1 ${cleanedCommandName}; exit 0; }`,
            (error, stdout) => {
                callback(null, !!stdout);
            });
            return;
        }
 
        localExecutable(commandName, callback);
    });
};
 
const commandExistsWindows = (commandName, cleanedCommandName, callback) => {
    if (/[\x00-\x1f<>:"\|\?\*]/.test(commandName)) {
        callback(null, false);
        return;
    }
    exec(`where ${cleanedCommandName}`,
        (error) => {
            if (error !== null) {
                callback(null, false);
            } else {
                callback(null, true);
            }
        });
};
 
const commandExistsUnixSync = (commandName, cleanedCommandName) => {
  E  if (fileNotExistsSync(commandName)) {
        try {
            const stdout = execSync(`command -v ${cleanedCommandName
            } 2>/dev/null`
              + ` && { echo >&1 ${cleanedCommandName}; exit 0; }`);
            return !!stdout;
        } catch (error) {
            return false;
        }
    }
    return localExecutableSync(commandName);
};
 
const commandExistsWindowsSync = (commandName, cleanedCommandName) => {
    if (/[\x00-\x1f<>:"\|\?\*]/.test(commandName)) {
        return false;
    }
    try {
        const stdout = execSync(`where ${cleanedCommandName}`, { stdio: [] });
        return !!stdout;
    } catch (error) {
        return false;
    }
};
 
let cleanInput = (s) => {
  I  if (/[^A-Za-z0-9_\/:=-]/.test(s)) {
        s = `'${s.replace(/'/g, "'\\''")}'`;
        s = s.replace(/^(?:'')+/g, '') // unduplicate single-quote at the beginning
            .replace(/\\'''/g, "\\'"); // remove non-escaped single-quote if there are enclosed between 2 escaped
    }
    return s;
};
 
Iif (isUsingWindows) {
    cleanInput = (s) => {
        const isPathName = /[\\]/.test(s);
        if (isPathName) {
            const dirname = `"${path.dirname(s)}"`;
            const basename = `"${path.basename(s)}"`;
            return `${dirname}:${basename}`;
        }
        return `"${s}"`;
    };
}
 
const commandExists = (commandName, callback) => {
    const cleanedCommandName = cleanInput(commandName);
    if (!callback && typeof Promise !== 'undefined') {
        return new Promise(((resolve, reject) => {
            commandExists(commandName, (error, output) => {
        E        if (output) {
                    resolve(commandName);
                } else {
                    reject(error);
                }
            });
        }));
    }
  I  if (isUsingWindows) {
        commandExistsWindows(commandName, cleanedCommandName, callback);
    } else {
        commandExistsUnix(commandName, cleanedCommandName, callback);
    }
};
 
const commandExistsSync = (commandName) => {
    const cleanedCommandName = cleanInput(commandName);
  I  if (isUsingWindows) {
        return commandExistsWindowsSync(commandName, cleanedCommandName);
    }
    return commandExistsUnixSync(commandName, cleanedCommandName);
};
 
const openCommand = process.platform == 'darwin' ? 'open' : process.platform == 'win32' ? 'start' : 'xdg-open';
 
export { executeAsync, execCLI, commandExists, commandExistsSync, openCommand, executeTelnet };
 
export default {
    executeAsync,
    execCLI,
    openCommand,
    executeTelnet
};