"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MigratedDataFactory = void 0;
exports.applyPrettierFormatting = applyPrettierFormatting;
const tslib_1 = require("tslib");
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
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 platform_1 = require("../../../../modules/platform");
const scm_1 = require("../../../../modules/platform/scm");
const fs_1 = require("../../../../util/fs");
const json_writer_1 = require("../../../../util/json-writer");
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(filename, content, parser, indent) {
    try {
        logger_1.logger.trace('applyPrettierFormatting - START');
        const fileList = await scm_1.scm.getFileList();
        let prettierExists = fileList.some((file) => prettierConfigFilenames.has(file));
        const editorconfigExists = fileList.some((file) => file === '.editorconfig');
        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',
        };
        if (editorconfigExists) {
            const editorconf = await json_writer_1.EditorConfig.getCodeFormat(filename);
            // https://github.com/prettier/prettier/blob/bab892242a1f9d8fcae50514b9304bf03f2e25ab/src/config/editorconfig/editorconfig-to-prettier.js#L47
            if (editorconf.maxLineLength) {
                options.printWidth = is_1.default.number(editorconf.maxLineLength)
                    ? editorconf.maxLineLength
                    : Number.POSITIVE_INFINITY;
            }
            // TODO: support editor config `indent_style` and `indent_size`
        }
        return (0, expose_cjs_1.prettier)().format(content, options);
    }
    finally {
        logger_1.logger.trace('applyPrettierFormatting - END');
    }
}
class MigratedDataFactory {
    // singleton
    static data;
    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(filename, content, parser, indent);
    }
    static async build() {
        let res = null;
        try {
            const { configFileName, 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;
            // TODO #22198
            const raw = await platform_1.platform.getRawFile(configFileName);
            const indent = (0, detect_indent_1.default)(raw ?? '');
            // indent defaults to 2 spaces
            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