"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MigratedDataFactory = void 0;
const tslib_1 = require("tslib");
const detect_indent_1 = tslib_1.__importDefault(require("detect-indent"));
const json5_1 = tslib_1.__importDefault(require("json5"));
const migration_1 = require("../../../../config/migration");
const logger_1 = require("../../../../logger");
const fs_1 = require("../../../../util/fs");
const merge_1 = require("../../init/merge");
class MigratedDataFactory {
    static async getAsync() {
        if (this.data) {
            return this.data;
        }
        const migrated = await this.build();
        if (!migrated) {
            return null;
        }
        this.data = migrated;
        return this.data;
    }
    static reset() {
        this.data = null;
    }
    static async build() {
        let res = null;
        try {
            const rc = await (0, merge_1.detectRepoFileConfig)();
            const configFileParsed = rc?.configFileParsed || {};
            // get migrated config
            const { isMigrated, migratedConfig } = (0, migration_1.migrateConfig)(configFileParsed);
            if (!isMigrated) {
                return null;
            }
            delete migratedConfig.errors;
            delete migratedConfig.warnings;
            const filename = rc.configFileName ?? '';
            const raw = await (0, fs_1.readLocalFile)(filename, 'utf8');
            // indent defaults to 2 spaces
            // TODO #7154
            const indent = (0, detect_indent_1.default)(raw).indent ?? '  ';
            let content;
            if (filename.endsWith('.json5')) {
                content = json5_1.default.stringify(migratedConfig, undefined, indent);
            }
            else {
                content = JSON.stringify(migratedConfig, undefined, indent);
            }
            if (!content.endsWith('\n')) {
                content += '\n';
            }
            res = { content, filename };
        }
        catch (err) {
            logger_1.logger.debug({ err }, 'MigratedDataFactory.getAsync() Error initializing renovate MigratedData');
        }
        return res;
    }
}
exports.MigratedDataFactory = MigratedDataFactory;
//# sourceMappingURL=migrated-data.js.map