"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const child_process_1 = require("child_process");
const fs = require("fs");
const path_1 = require("path");
const util_1 = require("util");
const utils_1 = require("../utils");
const childrenProcesses = [];
let tmpDirectory = null;
function setTmpDirectory(dir) {
    tmpDirectory = dir;
    if (dir) {
        rimraf(dir);
        process.once('uncaughtException', () => cleanup(true));
        process.once('exit', () => cleanup());
        process.once('SIGINT', () => cleanup());
        process.once('SIGTERM', () => cleanup());
    }
}
exports.setTmpDirectory = setTmpDirectory;
function cleanup(didError = false) {
    if (tmpDirectory) {
        killChildren();
    }
    setTimeout(() => {
        if (tmpDirectory) {
            rimraf(tmpDirectory);
            tmpDirectory = null;
        }
        process.exit(didError ? 1 : 0);
    }, 200);
}
exports.cleanup = cleanup;
function killChildren() {
    childrenProcesses.forEach(p => p.kill('SIGINT'));
}
exports.killChildren = killChildren;
function npm(command, projectPath, stdio = 'ignore') {
    return new Promise((resolve, reject) => {
        const p = child_process_1.spawn('npm', [command], {
            shell: true,
            stdio,
            cwd: projectPath
        });
        p.once('exit', () => resolve());
        p.once('error', reject);
        childrenProcesses.push(p);
    });
}
exports.npm = npm;
function rimraf(dirPath) {
    if (fs.existsSync(dirPath)) {
        fs.readdirSync(dirPath).forEach(entry => {
            const entryPath = path_1.join(dirPath, entry);
            if (fs.lstatSync(entryPath).isDirectory()) {
                rimraf(entryPath);
            }
            else {
                fs.unlinkSync(entryPath);
            }
        });
        fs.rmdirSync(dirPath);
    }
}
exports.rimraf = rimraf;
function onlyUnix(str) {
    return isWin() ? str : '';
}
exports.onlyUnix = onlyUnix;
function printDuration(duration) {
    if (duration > 1000) {
        return `in ${(duration / 1000).toFixed(2)} s`;
    }
    else {
        const ms = parseFloat(duration.toFixed(3));
        return `in ${ms} ms`;
    }
}
exports.printDuration = printDuration;
function isWin() {
    return process.platform === 'win32';
}
exports.isWin = isWin;
function terminalPrompt() {
    return isWin() ? '>' : '$';
}
exports.terminalPrompt = terminalPrompt;
exports.renameAsync = util_1.promisify(fs.rename);
function nodeVersionWarning() {
    try {
        const v = process.version.replace('v', '').split('.');
        const major = parseInt(v[0], 10);
        const minor = parseInt(v[1], 10);
        if (major < 10) {
            utils_1.logWarning(`Your current version of Node is ${process.version}, however the recommendation is a minimum of Node 10.x LTS.`);
        }
    }
    catch (e) {
        return;
    }
}
exports.nodeVersionWarning = nodeVersionWarning;
//# sourceMappingURL=utils.js.map