"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.writeUpdates = exports.canSkipBranchUpdateCheck = void 0;
const tslib_1 = require("tslib");
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
const hasha_1 = tslib_1.__importDefault(require("hasha"));
const safe_stable_stringify_1 = tslib_1.__importDefault(require("safe-stable-stringify"));
const logger_1 = require("../../../logger");
const manager_1 = require("../../../modules/manager");
const repository_1 = require("../../../util/cache/repository");
const git_1 = require("../../../util/git");
const limits_1 = require("../../global/limits");
const types_1 = require("../../types");
const branch_1 = require("../update/branch");
const limits_2 = require("./limits");
function canSkipBranchUpdateCheck(branchCache, branchFingerprint) {
    if (!branchCache.branchFingerprint) {
        return false;
    }
    if (branchFingerprint !== branchCache.branchFingerprint) {
        logger_1.logger.debug('Branch fingerprint has changed, full check required');
        return false;
    }
    logger_1.logger.debug('Branch fingerprint is unchanged, updates check can be skipped');
    return true;
}
exports.canSkipBranchUpdateCheck = canSkipBranchUpdateCheck;
async function writeUpdates(config, allBranches) {
    const branches = allBranches;
    logger_1.logger.debug(`Processing ${branches.length} branch${branches.length === 1 ? '' : 'es'}: ${branches
        .map((b) => b.branchName)
        .sort()
        .join(', ')}`);
    const cache = (0, repository_1.getCache)();
    const { branches: cachedBranches = [] } = cache;
    const prsRemaining = await (0, limits_2.getPrsRemaining)(config, branches);
    logger_1.logger.debug({ prsRemaining }, 'Calculated maximum PRs remaining this run');
    (0, limits_1.setMaxLimit)(limits_1.Limit.PullRequests, prsRemaining);
    const branchesRemaining = await (0, limits_2.getBranchesRemaining)(config, branches);
    logger_1.logger.debug({ branchesRemaining }, 'Calculated maximum branches remaining this run');
    (0, limits_1.setMaxLimit)(limits_1.Limit.Branches, branchesRemaining);
    for (const branch of branches) {
        const { baseBranch, branchName } = branch;
        const meta = { branch: branchName };
        if (config.baseBranches?.length && baseBranch) {
            meta['baseBranch'] = baseBranch;
        }
        (0, logger_1.addMeta)(meta);
        const branchExisted = (0, git_1.branchExists)(branchName);
        let branchCache = {};
        if (branchExisted && config.repositoryCache === 'enabled') {
            branchCache =
                cachedBranches?.find((br) => br.branchName === branchName) ??
                    {};
            if (Object.keys(branchCache).length === 0) {
                logger_1.logger.debug(`No branch cache found for ${branch.branchName}`);
            }
        }
        const branchManagersFingerprint = (0, hasha_1.default)([
            ...new Set(branch.upgrades
                .map((upgrade) => manager_1.hashMap.get(upgrade.manager) ?? upgrade.manager)
                .filter(is_1.default.string)),
        ].sort());
        const branchFingerprint = (0, hasha_1.default)([
            (0, safe_stable_stringify_1.default)(branch),
            branchManagersFingerprint,
        ]);
        branch.skipBranchUpdate = canSkipBranchUpdateCheck(branchCache, branchFingerprint);
        const res = await (0, branch_1.processBranch)(branch);
        branch.prBlockedBy = res?.prBlockedBy;
        branch.prNo = res?.prNo;
        branch.result = res?.result;
        branch.branchFingerprint = res?.commitSha
            ? branchFingerprint
            : branchCache.branchFingerprint;
        if (branch.result === types_1.BranchResult.Automerged &&
            branch.automergeType !== 'pr-comment') {
            // Stop processing other branches because base branch has been changed
            return 'automerged';
        }
        if (!branchExisted && (0, git_1.branchExists)(branch.branchName)) {
            (0, limits_1.incLimitedValue)(limits_1.Limit.Branches);
        }
    }
    (0, logger_1.removeMeta)(['branch', 'baseBranch']);
    return 'done';
}
exports.writeUpdates = writeUpdates;
//# sourceMappingURL=write.js.map