"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MigratedDataFactory = exports.applyPrettierFormatting = 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 upath_1 = tslib_1.__importDefault(require("upath"));
const migration_1 = require("../../../../config/migration");
const expose_cjs_1 = require("../../../../expose.cjs");
const logger_1 = require("../../../../logger");
const fs_1 = require("../../../../util/fs");
const git_1 = require("../../../../util/git");
const merge_1 = require("../../init/merge");
const prettierConfigFilenames = new Set([
    '.prettierrc',
    '.prettierrc.json',
    '.prettierrc.yml',
    '.prettierrc.yaml',
    '.prettierrc.json5',
    '.prettierrc.js',
    '.prettierrc.cjs',
    'prettier.config.js',
    'prettier.config.cjs',
    '.prettierrc.toml',
]);
async function applyPrettierFormatting(content, parser, indent) {
    try {
        logger_1.logger.trace('applyPrettierFormatting - START');
        const fileList = await (0, git_1.getFileList)();
        let prettierExists = fileList.some((file) => prettierConfigFilenames.has(file));
        if (!prettierExists) {
            try {
                const packageJsonContent = await (0, fs_1.readLocalFile)('package.json', 'utf8');
                prettierExists =
                    packageJsonContent && JSON.parse(packageJsonContent).prettier;
            }
            catch {
                logger_1.logger.warn('applyPrettierFormatting - Error processing package.json file');
            }
        }
        if (!prettierExists) {
            return content;
        }
        const options = {
            parser,
            tabWidth: indent?.amount === 0 ? 2 : indent?.amount,
            useTabs: indent?.type === 'tab',
        };
        return (0, expose_cjs_1.prettier)().format(content, options);
    }
    finally {
        logger_1.logger.trace('applyPrettierFormatting - END');
    }
}
exports.applyPrettierFormatting = applyPrettierFormatting;
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 applyPrettierFormatting({ content, filename, indent, }) {
        const parser = upath_1.default.extname(filename).replace('.', '');
        return applyPrettierFormatting(content, parser, indent);
    }
    static async build() {
        let res = null;
        try {
            const { configFileName, configFileRaw: raw, configFileParsed = {}, } = await (0, merge_1.detectRepoFileConfig)();
            // get migrated config
            const { isMigrated, migratedConfig } = (0, migration_1.migrateConfig)(configFileParsed);
            if (!isMigrated) {
                return null;
            }
            delete migratedConfig.errors;
            delete migratedConfig.warnings;
            // indent defaults to 2 spaces
            // TODO #7154
            const indent = (0, detect_indent_1.default)(raw);
            const indentSpace = indent.indent ?? '  ';
            const filename = configFileName;
            let content;
            if (filename.endsWith('.json5')) {
                content = json5_1.default.stringify(migratedConfig, undefined, indentSpace);
            }
            else {
                content = JSON.stringify(migratedConfig, undefined, indentSpace);
            }
            if (!content.endsWith('\n')) {
                content += '\n';
            }
            res = { content, filename, indent };
        }
        catch (err) {
            logger_1.logger.debug({ err }, 'MigratedDataFactory.getAsync() Error initializing renovate MigratedData');
        }
        return res;
    }
}
exports.MigratedDataFactory = MigratedDataFactory;
//# sourceMappingURL=migrated-data.js.map