"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getOnboardingPr = exports.isOnboarded = void 0;
const app_strings_1 = require("../../../../config/app-strings");
const error_messages_1 = require("../../../../constants/error-messages");
const logger_1 = require("../../../../logger");
const platform_1 = require("../../../../modules/platform");
const comment_1 = require("../../../../modules/platform/comment");
const scm_1 = require("../../../../modules/platform/scm");
const repository_1 = require("../../../../util/cache/repository");
const fs_1 = require("../../../../util/fs");
const git_1 = require("../../../../util/git");
async function findFile(fileName) {
    logger_1.logger.debug(`findFile(${fileName})`);
    const fileList = await scm_1.scm.getFileList();
    return fileList.includes(fileName);
}
async function configFileExists() {
    for (const fileName of app_strings_1.configFileNames) {
        if (fileName !== 'package.json' && (await findFile(fileName))) {
            logger_1.logger.debug(`Config file exists, fileName: ${fileName}`);
            return true;
        }
    }
    return false;
}
async function packageJsonConfigExists() {
    try {
        // TODO #22198
        const pJson = JSON.parse((await (0, fs_1.readLocalFile)('package.json', 'utf8')));
        if (pJson.renovate) {
            return true;
        }
    }
    catch (err) {
        // Do nothing
    }
    return false;
}
function closedPrExists(config) {
    return platform_1.platform.findPr({
        branchName: config.onboardingBranch,
        prTitle: config.onboardingPrTitle,
        state: '!open',
    });
}
async function isOnboarded(config) {
    logger_1.logger.debug('isOnboarded()');
    const title = `Action required: Add a Renovate config`;
    // Repo is onboarded if global config is bypassing onboarding and does not require a
    // configuration file.
    // The repo is considered "not onboarded" if:
    // - An onboarding cache is present, and
    // - The current default branch SHA matches the default SHA found in the cache
    // Also if there is a closed pr skip using cache as it is outdated
    if (config.requireConfig === 'optional' && config.onboarding === false) {
        // Return early and avoid checking for config files
        return true;
    }
    if (config.requireConfig === 'ignored') {
        logger_1.logger.debug('Config file will be ignored');
        return true;
    }
    const closedOnboardingPr = await closedPrExists(config);
    const cache = (0, repository_1.getCache)();
    const onboardingBranchCache = cache?.onboardingBranchCache;
    // if onboarding cache is present and base branch has not been updated branch is not onboarded
    // if closed pr exists then presence of onboarding cache doesn't matter as we need to skip onboarding
    if (config.onboarding &&
        !closedOnboardingPr &&
        onboardingBranchCache &&
        onboardingBranchCache.defaultBranchSha ===
            (0, git_1.getBranchCommit)(config.defaultBranch)) {
        logger_1.logger.debug('Onboarding cache is valid. Repo is not onboarded');
        return false;
    }
    if (cache.configFileName) {
        logger_1.logger.debug('Checking cached config file name');
        try {
            const configFileContent = await platform_1.platform.getJsonFile(cache.configFileName);
            if (configFileContent) {
                if (cache.configFileName !== 'package.json' ||
                    configFileContent.renovate) {
                    logger_1.logger.debug('Existing config file confirmed');
                    logger_1.logger.debug({ fileName: cache.configFileName, config: configFileContent }, 'Repository config');
                    return true;
                }
            }
        }
        catch (err) {
            // probably file doesn't exist
        }
        logger_1.logger.debug('Existing config file no longer exists');
        delete cache.configFileName;
    }
    if (await configFileExists()) {
        await platform_1.platform.ensureIssueClosing(title);
        return true;
    }
    logger_1.logger.debug('config file not found');
    if (await packageJsonConfigExists()) {
        logger_1.logger.debug('package.json contains config');
        await platform_1.platform.ensureIssueClosing(title);
        return true;
    }
    // If onboarding has been disabled and config files are required then the
    // repository has not been onboarded yet
    if (config.requireConfig === 'required' && config.onboarding === false) {
        throw new Error(error_messages_1.REPOSITORY_NO_CONFIG);
    }
    if (!closedOnboardingPr) {
        logger_1.logger.debug('Found no closed onboarding PR');
        return false;
    }
    logger_1.logger.debug('Found closed onboarding PR');
    if (config.requireConfig === 'optional') {
        logger_1.logger.debug('Config not mandatory so repo is considered onboarded');
        return true;
    }
    logger_1.logger.debug('Repo is not onboarded and no merged PRs exist');
    if (!config.suppressNotifications.includes('onboardingClose')) {
        // ensure PR comment
        await (0, comment_1.ensureComment)({
            number: closedOnboardingPr.number,
            topic: `Renovate is disabled`,
            content: `Renovate is disabled because there is no Renovate configuration file. To enable Renovate, you can either (a) change this PR's title to get a new onboarding PR, and merge the new onboarding PR, or (b) create a Renovate config file, and commit that file to your base branch.`,
        });
    }
    throw new Error(error_messages_1.REPOSITORY_CLOSED_ONBOARDING);
}
exports.isOnboarded = isOnboarded;
async function getOnboardingPr(config) {
    return await platform_1.platform.getBranchPr(config.onboardingBranch);
}
exports.getOnboardingPr = getOnboardingPr;
//# sourceMappingURL=check.js.map