"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const constants_1 = require("@pnpm/constants");
const find_packages_1 = require("find-packages");
const path = require("path");
const read_yaml_file_1 = require("read-yaml-file");
const packageIsInstallable_1 = require("./packageIsInstallable");
exports.default = async (workspaceRoot, opts) => {
    const packagesManifest = await requirePackagesManifest(workspaceRoot);
    const pkgs = await find_packages_1.default(workspaceRoot, {
        ignore: [
            '**/node_modules/**',
            '**/bower_components/**',
        ],
        patterns: packagesManifest && packagesManifest.packages || undefined,
    });
    pkgs.sort((pkg1, pkg2) => pkg1.path.localeCompare(pkg2.path));
    for (const pkg of pkgs) {
        packageIsInstallable_1.default(pkg.path, pkg.manifest, opts); // tslint:disable-line:no-any
    }
    return pkgs;
};
async function requirePackagesManifest(dir) {
    try {
        return await read_yaml_file_1.default(path.join(dir, constants_1.WORKSPACE_MANIFEST_FILENAME));
    }
    catch (err) {
        if (err['code'] === 'ENOENT') { // tslint:disable-line
            return null;
        }
        throw err;
    }
}
function arrayOfLocalPackagesToMap(pkgs) {
    return pkgs.reduce((acc, pkg) => {
        if (!acc[pkg.manifest.name]) {
            acc[pkg.manifest.name] = {};
        }
        acc[pkg.manifest.name][pkg.manifest.version] = {
            directory: pkg.path,
            package: pkg.manifest,
        };
        return acc;
    }, {});
}
exports.arrayOfLocalPackagesToMap = arrayOfLocalPackagesToMap;
