"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ensureConfigMigrationPr = void 0;
const tslib_1 = require("tslib");
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
const global_1 = require("../../../../config/global");
const logger_1 = require("../../../../logger");
const platform_1 = require("../../../../modules/platform");
const pr_body_1 = require("../../../../modules/platform/pr-body");
const emoji_1 = require("../../../../util/emoji");
const git_1 = require("../../../../util/git");
const template = tslib_1.__importStar(require("../../../../util/template"));
const url_1 = require("../../../../util/url");
const pr_1 = require("../../update/pr");
const labels_1 = require("../../update/pr/labels");
const participants_1 = require("../../update/pr/participants");
const commit_message_1 = require("../branch/commit-message");
const common_1 = require("../common");
async function ensureConfigMigrationPr(config, migratedConfigData) {
    logger_1.logger.debug('ensureConfigMigrationPr()');
    const docsLink = (0, url_1.joinUrlParts)(config.productLinks?.documentation ?? '', 'configuration-options/#configmigration');
    const branchName = (0, common_1.getMigrationBranchName)(config);
    const commitMessageFactory = new commit_message_1.ConfigMigrationCommitMessageFactory(config, migratedConfigData.filename);
    const prTitle = commitMessageFactory.getPrTitle();
    const existingPr = await platform_1.platform.getBranchPr(branchName);
    const filename = migratedConfigData.filename;
    logger_1.logger.debug('Filling in config migration PR template');
    let prBody = `The Renovate config in this repository needs migrating. Typically this is because one or more configuration options you are using have been renamed.

  You don't need to merge this PR right away, because Renovate will continue to migrate these fields internally each time it runs. But later some of these fields may be fully deprecated and the migrations removed. So it's a good idea to merge this migration PR soon. \n\n`;
    prBody += (0, emoji_1.emojify)(`

${filename.endsWith('.json5')
        ? `#### [PLEASE NOTE](${docsLink}): ` +
            `JSON5 config file migrated! All comments & trailing commas were removed.`
        : ''}

:no_bell: **Ignore**: Close this PR and you won't be reminded about config migration again, but one day your current config may no longer be valid.

:question: Got questions? Does something look wrong to you? Please don't hesitate to [request help here](${
    // TODO: types (#7154)
    // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
    config.productLinks?.help}).\n\n`);
    if (is_1.default.string(config.prHeader)) {
        prBody = `${template.compile(config.prHeader, config)}\n\n${prBody}`;
    }
    if (is_1.default.string(config.prFooter)) {
        prBody = `${prBody}\n---\n\n${template.compile(config.prFooter, config)}\n`;
    }
    logger_1.logger.trace({ prBody }, 'prBody');
    prBody = platform_1.platform.massageMarkdown(prBody);
    if (existingPr) {
        logger_1.logger.debug('Found open migration PR');
        // Check if existing PR needs updating
        const prBodyHash = (0, pr_body_1.hashBody)(prBody);
        if (existingPr.bodyStruct?.hash === prBodyHash &&
            existingPr.title === prTitle) {
            logger_1.logger.debug({ pr: existingPr.number }, `Does not need updating`);
            return;
        }
        // PR must need updating
        if (global_1.GlobalConfig.get('dryRun')) {
            logger_1.logger.info('DRY-RUN: Would update migration PR');
        }
        else {
            await platform_1.platform.updatePr({
                number: existingPr.number,
                prTitle,
                prBody,
            });
            logger_1.logger.info({ pr: existingPr.number }, 'Migration PR updated');
        }
        return;
    }
    logger_1.logger.debug('Creating migration PR');
    const labels = (0, labels_1.prepareLabels)(config);
    try {
        if (global_1.GlobalConfig.get('dryRun')) {
            logger_1.logger.info('DRY-RUN: Would create migration PR');
        }
        else {
            const pr = await platform_1.platform.createPr({
                sourceBranch: branchName,
                // TODO #7154
                targetBranch: config.defaultBranch,
                prTitle,
                prBody,
                labels,
                platformOptions: (0, pr_1.getPlatformPrOptions)({
                    ...config,
                    automerge: false,
                }),
            });
            logger_1.logger.info({ pr: pr?.number }, 'Migration PR created');
            if (pr) {
                await (0, participants_1.addParticipants)(config, pr);
            }
        }
    }
    catch (err) {
        if (err.response?.statusCode === 422 &&
            err.response?.body?.errors?.[0]?.message?.startsWith('A pull request already exists')) {
            logger_1.logger.warn({ err }, 'Migration PR already exists but cannot find it. It was probably created by a different user.');
            await (0, git_1.deleteBranch)(branchName);
            return;
        }
        throw err;
    }
}
exports.ensureConfigMigrationPr = ensureConfigMigrationPr;
//# sourceMappingURL=index.js.map