"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 fs = require("mz/fs");
const mkdirp = require("mkdirp-promise");
const rimraf = require("rimraf-then");
const bole = require("bole");
const logger = bole('link-dir');
function linkDir(existingDir, newDir) {
    return __awaiter(this, void 0, void 0, function* () {
        const stage = `${newDir}+stage`;
        try {
            yield rimraf(stage);
            yield hardlinkDir(existingDir, stage);
            yield rimraf(newDir);
            yield fs.rename(stage, newDir);
        }
        catch (err) {
            try {
                yield rimraf(stage);
            }
            catch (err) { }
            throw err;
        }
    });
}
function hardlinkDir(existingDir, newDir) {
    return __awaiter(this, void 0, void 0, function* () {
        yield mkdirp(newDir);
        const dirs = yield fs.readdir(existingDir);
        yield Promise.all(dirs
            .map((relativePath) => __awaiter(this, void 0, void 0, function* () {
            const existingPath = path.join(existingDir, relativePath);
            const newPath = path.join(newDir, relativePath);
            const stat = yield fs.lstat(existingPath);
            if (stat.isSymbolicLink() || stat.isFile()) {
                return safeLink(existingPath, newPath, stat);
            }
            if (stat.isDirectory()) {
                return hardlinkDir(existingPath, newPath);
            }
        })));
    });
}
function safeLink(existingPath, newPath, stat) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            yield fs.link(existingPath, newPath);
        }
        catch (err) {
            // shouldn't normally happen, but if the file was already somehow linked,
            // the installation should not fail
            if (err.code === 'EEXIST') {
                return;
            }
            // might happen if package contains a broken symlink, we don't fail on this
            if (err.code === 'ENOENT' && stat.isSymbolicLink()) {
                logger.warn({
                    message: `Broken symlink found: ${existingPath}`,
                });
                return;
            }
            throw err;
        }
    });
}
// for backward compatibility
linkDir['default'] = linkDir;
module.exports = linkDir;
//# sourceMappingURL=index.js.map