"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 path = require("path");
const loadJsonFile = require("load-json-file");
const symlinkDir = require("symlink-dir");
const pnpm_logger_1 = require("pnpm-logger");
const install_1 = require("./install");
const expandTilde_1 = require("../fs/expandTilde");
const linkBins_1 = require("../link/linkBins");
const extendOptions_1 = require("./extendOptions");
const linkLogger = pnpm_logger_1.default('link');
function link(linkFrom, linkTo, maybeOpts) {
    return __awaiter(this, void 0, void 0, function* () {
        const opts = extendOptions_1.default(maybeOpts);
        yield install_1.install(Object.assign({}, opts, { prefix: linkFrom, global: false }));
        const destModules = path.join(linkTo, 'node_modules');
        yield linkToModules(linkFrom, destModules);
        const bin = path.join(destModules, '.bin');
        yield linkBins_1.linkPkgBins(linkFrom, bin);
    });
}
exports.default = link;
function linkToModules(linkFrom, modules) {
    return __awaiter(this, void 0, void 0, function* () {
        const pkg = yield loadJsonFile(path.join(linkFrom, 'package.json'));
        const dest = path.join(modules, pkg.name);
        linkLogger.info(`${dest} -> ${linkFrom}`);
        yield symlinkDir(linkFrom, dest);
    });
}
function linkFromGlobal(pkgName, linkTo, maybeOpts) {
    return __awaiter(this, void 0, void 0, function* () {
        const opts = extendOptions_1.default(maybeOpts);
        const globalPkgPath = expandTilde_1.default(maybeOpts.globalPrefix);
        const linkedPkgPath = path.join(globalPkgPath, 'node_modules', pkgName);
        yield link(linkedPkgPath, linkTo, opts);
    });
}
exports.linkFromGlobal = linkFromGlobal;
function linkToGlobal(linkFrom, maybeOpts) {
    return __awaiter(this, void 0, void 0, function* () {
        const opts = extendOptions_1.default(maybeOpts);
        opts.global = true; // bins will be linked to the global bin path
        const globalPkgPath = expandTilde_1.default(maybeOpts.globalPrefix);
        yield link(linkFrom, globalPkgPath, opts);
    });
}
exports.linkToGlobal = linkToGlobal;
//# sourceMappingURL=link.js.map