"use strict";
/**********************************************************************
 * Copyright (c) 2018-2021 Red Hat, Inc.
 *
 * This program and the accompanying materials are made
 * available under the terms of the Eclipse Public License 2.0
 * which is available at https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 ***********************************************************************/
Object.defineProperty(exports, "__esModule", { value: true });
exports.link = exports.handleCommand = exports.builder = void 0;
/**
 * A command to yarn link theia dependencies into che-theia
 * @author Thomas Mäder
 */
const fs = require("fs-extra");
const os = require("os");
const path = require("path");
const command_1 = require("./command");
exports.builder = {
    theia: {
        describe: 'Path of the theia project source',
        requiresArg: true,
        type: 'string',
        demandOption: false,
    },
    'che-theia': {
        describe: 'Path of the che-theia project source',
        requiresArg: true,
        type: 'string',
        demandOption: false,
    },
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function handleCommand(args) {
    const theiaDir = args.theia || path.resolve(process.cwd(), '../theia');
    const cheTheiaDir = args['che-theia'] || process.cwd();
    const cfg = await new command_1.Command(cheTheiaDir).exec('yarn --silent --json --non-interactive config current');
    try {
        const yarnConfig = JSON.parse(JSON.parse(cfg).data);
        let linkDir = yarnConfig['linkFolder'] || path.resolve(os.homedir(), '.yarn/link');
        await fs.ensureDir(linkDir);
        linkDir = await fs.realpath(linkDir);
        await link(cheTheiaDir, theiaDir, linkDir);
    }
    catch (e) {
        console.error(e);
    }
}
exports.handleCommand = handleCommand;
async function link(cheTheiaProjectPath, theiaProjectPath, yarnLinkFolder) {
    await linkTheia(yarnLinkFolder, theiaProjectPath);
    await linkChe(yarnLinkFolder, cheTheiaProjectPath);
}
exports.link = link;
async function linkTheia(yarnLinkFolder, theiaProjectPath) {
    for (const rootName of ['packages', 'dev-packages', 'examples']) {
        const rootPath = path.resolve(theiaProjectPath, rootName);
        const folderNames = await fs.readdir(rootPath);
        for (const folderName of folderNames) {
            await new command_1.Command(path.resolve(rootPath, folderName)).exec(`yarn link --link-folder=${yarnLinkFolder}`);
        }
    }
}
async function linkChe(yarnLinkFolder, cheTheiaProjectPath) {
    const packages = await fs.readdir(path.resolve(yarnLinkFolder, '@theia'));
    const cmd = new command_1.Command(cheTheiaProjectPath);
    for (const pkg of packages) {
        await cmd.exec(`yarn link @theia/${pkg}`);
    }
}
//# sourceMappingURL=link.js.map