"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.safeYarn = safeYarn;
const chalk_1 = __importDefault(require("chalk"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const utils_js_1 = require("../utils.js");
/**
 * Run a yarn command at the workspace root while preserving nested repositories'
 * yarn.lock files. Used when the workspace contains sibling repos (via mrgit)
 * whose own lockfiles should not be clobbered by a root-level `yarn install`.
 *
 * Reads mrgit.json to determine which nested repos exist. If mrgit.json is
 * missing, falls back to plain yarn behavior.
 */
async function safeYarn(args) {
    const mrgitPath = path_1.default.join(process.cwd(), 'mrgit.json');
    const yarnCmd = `yarn ${args.join(' ')}`;
    if (process.env.LINKED_YARN_DRY_RUN) {
        console.log(chalk_1.default.cyan(`[dry-run] would execute: ${yarnCmd}`));
        console.log(chalk_1.default.cyan(`[dry-run] received args: ${JSON.stringify(args)}`));
        return;
    }
    if (!fs_extra_1.default.existsSync(mrgitPath)) {
        await (0, utils_js_1.execp)(yarnCmd, true, false);
        return;
    }
    const mrgit = JSON.parse(fs_extra_1.default.readFileSync(mrgitPath, 'utf8'));
    const nestedRepos = Object.keys(mrgit.dependencies || {}).map((dep) => {
        // mrgit repo keys can be scoped (e.g. @_linked/core) or plain (the-game).
        // The folder they land in is `packages/<last-segment>`.
        const folder = dep.includes('/') ? dep.split('/').pop() : dep;
        return { name: dep, path: path_1.default.join(process.cwd(), 'packages', folder) };
    });
    console.log(chalk_1.default.magenta(`Preserving ${nestedRepos.length} nested yarn.lock files during yarn run`));
    const backedUp = [];
    try {
        // Back up nested lockfiles
        for (const repo of nestedRepos) {
            const lockPath = path_1.default.join(repo.path, 'yarn.lock');
            if (fs_extra_1.default.existsSync(lockPath)) {
                fs_extra_1.default.renameSync(lockPath, lockPath + '.bak');
                fs_extra_1.default.createFileSync(lockPath);
                backedUp.push(repo.path);
            }
        }
        // Run the yarn command
        await (0, utils_js_1.execp)(yarnCmd, true, false);
    }
    finally {
        // Restore nested lockfiles
        for (const repoPath of backedUp) {
            const lockPath = path_1.default.join(repoPath, 'yarn.lock');
            const bakPath = lockPath + '.bak';
            if (fs_extra_1.default.existsSync(bakPath)) {
                if (fs_extra_1.default.existsSync(lockPath))
                    fs_extra_1.default.unlinkSync(lockPath);
                fs_extra_1.default.renameSync(bakPath, lockPath);
            }
        }
    }
}
//# sourceMappingURL=safe-yarn.js.map