"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 core_loggers_1 = require("@pnpm/core-loggers");
const package_bins_1 = require("@pnpm/package-bins");
const utils_1 = require("@pnpm/utils");
const path = require("path");
const rimraf = require("rimraf-then");
function removeDirectDependency(dependency, opts) {
    return __awaiter(this, void 0, void 0, function* () {
        const results = yield Promise.all([
            removeBins(dependency.name, opts),
            !opts.dryRun && remove(path.join(opts.modulesDir, dependency.name)),
        ]);
        const uninstalledPkg = results[0];
        if (!opts.muteLogs) {
            core_loggers_1.rootLogger.debug({
                prefix: opts.prefix,
                removed: {
                    dependencyType: dependency.dev && 'dev' || dependency.optional && 'optional' || 'prod',
                    name: dependency.name,
                    version: uninstalledPkg && uninstalledPkg.version,
                },
            });
        }
    });
}
exports.default = removeDirectDependency;
function removeBins(uninstalledPkg, opts) {
    return __awaiter(this, void 0, void 0, function* () {
        const uninstalledPkgPath = path.join(opts.modulesDir, uninstalledPkg);
        const uninstalledPkgJson = yield utils_1.safeReadPackageFromDir(uninstalledPkgPath);
        if (!uninstalledPkgJson)
            return;
        const cmds = yield package_bins_1.default(uninstalledPkgJson, uninstalledPkgPath);
        if (!opts.dryRun) {
            // TODO: what about the .cmd bin files on Windows?
            yield Promise.all(cmds
                .map((cmd) => path.join(opts.bin, cmd.name))
                .map(remove));
        }
        return uninstalledPkgJson;
    });
}
function remove(p) {
    core_loggers_1.removalLogger.debug(p);
    return rimraf(p);
}
//# sourceMappingURL=removeDirectDependency.js.map