"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 readPkgUp = require('read-pkg-up');
const relSymlink_1 = require('../fs/relSymlink');
const install_1 = require('./install');
const expandTilde_1 = require('../fs/expandTilde');
const linkBins_1 = require('../install/linkBins');
const mkdirp_1 = require('../fs/mkdirp');
const extendOptions_1 = require('./extendOptions');
function linkFromRelative(linkTo, maybeOpts) {
    return __awaiter(this, void 0, void 0, function* () {
        const opts = extendOptions_1.default(maybeOpts);
        const cwd = opts && opts.cwd || process.cwd();
        const linkedPkgPath = path.resolve(cwd, linkTo);
        const currentModules = path.resolve(cwd, 'node_modules');
        yield install_1.install(Object.assign({}, opts, { cwd: linkedPkgPath }));
        yield mkdirp_1.default(currentModules);
        const pkg = yield readPkgUp({ cwd: linkedPkgPath });
        yield relSymlink_1.default(linkedPkgPath, path.resolve(currentModules, pkg.pkg.name));
        return linkBins_1.linkPkgBins(currentModules, linkedPkgPath);
    });
}
exports.linkFromRelative = linkFromRelative;
function linkFromGlobal(pkgName, maybeOpts) {
    const opts = extendOptions_1.default(maybeOpts);
    const globalPkgPath = expandTilde_1.default(opts.globalPath);
    const linkedPkgPath = path.join(globalPkgPath, 'node_modules', pkgName);
    return linkFromRelative(linkedPkgPath, opts);
}
exports.linkFromGlobal = linkFromGlobal;
function linkToGlobal(maybeOpts) {
    const opts = extendOptions_1.default(maybeOpts);
    const globalPkgPath = expandTilde_1.default(opts.globalPath);
    return linkFromRelative(opts.cwd, Object.assign({}, opts, {
        cwd: globalPkgPath
    }));
}
exports.linkToGlobal = linkToGlobal;
//# sourceMappingURL=link.js.map