"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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const logger_1 = require("@pnpm/logger");
const cmdShim = require("@zkochan/cmd-shim");
const isWindows = require("is-windows");
const mkdirp = require("mkdirp-promise");
const Module = require("module");
const fs = require("mz/fs");
const normalizePath = require("normalize-path");
const path = require("path");
const R = require("ramda");
const binify_1 = require("../binify");
const getPkgDirs_1 = require("../fs/getPkgDirs");
const safeReadPkg_1 = require("../fs/safeReadPkg");
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)));
    });
}
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_1.fromDir(target);
        if (!pkg) {
            logger_1.default.warn(`There's a directory in node_modules without package.json: ${target}`);
            return;
        }
        const cmds = yield binify_1.default(pkg, target);
        if (!cmds.length)
            return;
        yield mkdirp(binPath);
        yield Promise.all(cmds.map((cmd) => __awaiter(this, void 0, void 0, function* () {
            const externalBinPath = path.join(binPath, cmd.name);
            const nodePath = (yield getBinNodePaths(target)).join(path.delimiter);
            return cmdShim(cmd.path, externalBinPath, { nodePath });
        })));
    });
}
exports.linkPkgBins = linkPkgBins;
function getBinNodePaths(target) {
    return __awaiter(this, void 0, void 0, function* () {
        const targetRealPath = yield fs.realpath(target);
        return R.union(Module['_nodeModulePaths'](targetRealPath), // tslint:disable-line:no-string-literal
        Module['_nodeModulePaths'](target));
    });
}
//# sourceMappingURL=linkBins.js.map