"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.renovateRepository = renovateRepository;
exports.printRepositoryProblems = printRepositoryProblems;
const tslib_1 = require("tslib");
const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
const global_1 = require("../../config/global");
const secrets_1 = require("../../config/secrets");
const error_messages_1 = require("../../constants/error-messages");
const expose_cjs_1 = require("../../expose.cjs");
const instrumentation_1 = require("../../instrumentation");
const reporting_1 = require("../../instrumentation/reporting");
const logger_1 = require("../../logger");
const remap_1 = require("../../logger/remap");
const docker_1 = require("../../util/exec/docker");
const fs_1 = require("../../util/fs");
const git_1 = require("../../util/git");
const semantic_1 = require("../../util/git/semantic");
const queue = tslib_1.__importStar(require("../../util/http/queue"));
const throttle = tslib_1.__importStar(require("../../util/http/throttle"));
const split_1 = require("../../util/split");
const stats_1 = require("../../util/stats");
const cache_1 = require("./cache");
const common_1 = require("./common");
const config_migration_1 = require("./config-migration");
const dependency_dashboard_1 = require("./dependency-dashboard");
const error_1 = tslib_1.__importDefault(require("./error"));
const finalize_1 = require("./finalize");
const prune_1 = require("./finalize/prune");
const init_1 = require("./init");
const common_2 = require("./onboarding/common");
const pr_1 = require("./onboarding/pr");
const process_1 = require("./process");
const result_1 = require("./result");
// istanbul ignore next
async function renovateRepository(repoConfig, canRetry = true) {
    (0, split_1.splitInit)();
    let config = global_1.GlobalConfig.set((0, secrets_1.applySecretsToConfig)(repoConfig, undefined, false));
    await (0, docker_1.removeDanglingContainers)();
    (0, logger_1.setMeta)({ repository: config.repository });
    logger_1.logger.info({ renovateVersion: expose_cjs_1.pkg.version }, 'Repository started');
    logger_1.logger.trace({ config });
    let repoResult;
    queue.clear();
    throttle.clear();
    const localDir = global_1.GlobalConfig.get('localDir');
    try {
        await fs_extra_1.default.ensureDir(localDir);
        logger_1.logger.debug('Using localDir: ' + localDir);
        config = await (0, init_1.initRepo)(config);
        (0, split_1.addSplit)('init');
        const performExtract = config.repoIsOnboarded ||
            !common_2.OnboardingState.onboardingCacheValid ||
            common_2.OnboardingState.prUpdateRequested;
        const extractResult = performExtract
            ? await (0, instrumentation_1.instrument)('extract', () => (0, process_1.extractDependencies)(config))
            : emptyExtract(config);
        (0, reporting_1.addExtractionStats)(config, extractResult);
        const { branches, branchList, packageFiles } = extractResult;
        if (config.semanticCommits === 'auto') {
            config.semanticCommits = await (0, semantic_1.detectSemanticCommits)();
        }
        if (global_1.GlobalConfig.get('dryRun') !== 'lookup' &&
            global_1.GlobalConfig.get('dryRun') !== 'extract') {
            await (0, instrumentation_1.instrument)('onboarding', () => (0, pr_1.ensureOnboardingPr)(config, packageFiles, branches));
            (0, split_1.addSplit)('onboarding');
            const res = await (0, instrumentation_1.instrument)('update', () => (0, process_1.updateRepo)(config, branches));
            (0, logger_1.setMeta)({ repository: config.repository });
            (0, split_1.addSplit)('update');
            if (performExtract) {
                await (0, cache_1.setBranchCache)(branches); // update branch cache if performed extraction
            }
            if (res === 'automerged') {
                if (canRetry) {
                    logger_1.logger.info('Restarting repository job after automerge result');
                    const recursiveRes = await renovateRepository(repoConfig, false);
                    return recursiveRes;
                }
                logger_1.logger.debug(`Automerged but already retried once`);
            }
            else {
                const configMigrationRes = await (0, config_migration_1.configMigration)(config, branchList);
                await (0, dependency_dashboard_1.ensureDependencyDashboard)(config, branches, packageFiles, configMigrationRes);
            }
            await (0, finalize_1.finalizeRepo)(config, branchList);
            // TODO #22198
            repoResult = (0, result_1.processResult)(config, res);
        }
        printRepositoryProblems(config.repository);
    }
    catch (err) /* istanbul ignore next */ {
        (0, logger_1.setMeta)({ repository: config.repository });
        const errorRes = await (0, error_1.default)(config, err);
        const pruneWhenErrors = [
            error_messages_1.REPOSITORY_DISABLED_BY_CONFIG,
            error_messages_1.REPOSITORY_FORKED,
            error_messages_1.REPOSITORY_NO_CONFIG,
        ];
        if (pruneWhenErrors.includes(errorRes)) {
            await (0, prune_1.pruneStaleBranches)(config, []);
        }
        repoResult = (0, result_1.processResult)(config, errorRes);
    }
    if (localDir && !repoConfig.persistRepoData) {
        try {
            await (0, fs_1.deleteLocalFile)('.');
        }
        catch (err) /* istanbul ignore if */ {
            logger_1.logger.warn({ err }, 'localDir deletion error');
        }
    }
    try {
        await fs_extra_1.default.remove((0, fs_1.privateCacheDir)());
    }
    catch (err) /* istanbul ignore if */ {
        logger_1.logger.warn({ err }, 'privateCacheDir deletion error');
    }
    const splits = (0, split_1.getSplits)();
    logger_1.logger.debug(splits, 'Repository timing splits (milliseconds)');
    stats_1.PackageCacheStats.report();
    stats_1.DatasourceCacheStats.report();
    stats_1.HttpStats.report();
    stats_1.HttpCacheStats.report();
    stats_1.LookupStats.report();
    const cloned = (0, git_1.isCloned)();
    logger_1.logger.info({ cloned, durationMs: splits.total }, 'Repository finished');
    (0, remap_1.resetRepositoryLogLevelRemaps)();
    return repoResult;
}
// istanbul ignore next: renovateRepository is ignored
function emptyExtract(config) {
    return {
        branches: [],
        branchList: [config.onboardingBranch], // to prevent auto closing
        packageFiles: {},
    };
}
function printRepositoryProblems(repository) {
    const repoProblems = (0, common_1.extractRepoProblems)(repository);
    if (repoProblems.size) {
        logger_1.logger.debug({ repoProblems: Array.from(repoProblems) }, 'repository problems');
    }
}
//# sourceMappingURL=index.js.map