"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
const path = require("path");
const normalizePath = require("normalize-path");
const fs = require("mz/fs");
const mkdirp = require("mkdirp-promise");
const readPkg_1 = require("../fs/readPkg");
const getPkgDirs_1 = require("../fs/getPkgDirs");
const binify_1 = require("../binify");
const isWindows = require("is-windows");
const cmdShim = require("@zkochan/cmd-shim");
const pnpm_logger_1 = require("pnpm-logger");
const Module = require("module");
const union = require("lodash.union");
const IS_WINDOWS = isWindows();
function linkAllBins(modules, binPath, exceptPkgName) {
    return __awaiter(this, void 0, void 0, function* () {
        const pkgDirs = yield getPkgDirs_1.default(modules);
        return Promise.all(pkgDirs
            .map(pkgDir => normalizePath(pkgDir))
            .filter(pkgDir => !exceptPkgName || !pkgDir.endsWith(`/${exceptPkgName}`))
            .map((pkgDir) => linkPkgBins(pkgDir, binPath)));
    });
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = linkAllBins;
/**
 * Links executable into `node_modules/.bin`.
 */
function linkPkgBins(target, binPath) {
    return __awaiter(this, void 0, void 0, function* () {
        const pkg = yield safeReadPkg(target);
        if (!pkg) {
            pnpm_logger_1.default.warn(`There's a directory in node_modules without package.json: ${target}`);
            return;
        }
        if (!pkg.bin)
            return;
        const bins = binify_1.default(pkg);
        yield mkdirp(binPath);
        yield Promise.all(Object.keys(bins).map(function (bin) {
            return __awaiter(this, void 0, void 0, function* () {
                const externalBinPath = path.join(binPath, bin);
                const actualBin = bins[bin];
                const targetPath = path.join(target, actualBin);
                const nodePath = (yield getBinNodePaths(target)).join(path.delimiter);
                return cmdShim(targetPath, externalBinPath, { nodePath });
            });
        }));
    });
}
exports.linkPkgBins = linkPkgBins;
function getBinNodePaths(target) {
    return __awaiter(this, void 0, void 0, function* () {
        const targetRealPath = yield fs.realpath(target);
        return union(Module._nodeModulePaths(targetRealPath), Module._nodeModulePaths(target));
    });
}
function safeReadPkg(pkgPath) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            return yield readPkg_1.default(pkgPath);
        }
        catch (err) {
            if (err.code !== 'ENOENT')
                throw err;
            return null;
        }
    });
}
//# sourceMappingURL=linkBins.js.map