stylelint
Version:
A mighty CSS linter that helps you avoid errors and enforce conventions.
67 lines (52 loc) • 1.91 kB
JavaScript
// NOTICE: This file is generated by Rollup. To modify it,
// please instead edit the ESM counterpart and rebuild with Rollup (npm run build).
;
const constants = require('../constants.cjs');
const dynamicImport = require('./dynamicImport.cjs');
const fs = require('node:fs');
const index = require('../formatters/index.cjs');
const getConfigForFile = require('../getConfigForFile.cjs');
const getFormatterOptionsText = require('./getFormatterOptionsText.cjs');
const path = require('node:path');
/** @import {Formatter, InternalApi} from 'stylelint' */
/**
* @param {InternalApi} stylelint
* @returns {Promise<Formatter>}
*/
async function getFormatter(stylelint) {
const cwd = stylelint._options.cwd;
const configPath = stylelint._options.configFile || cwd;
let formatter = stylelint._options.formatter;
if (!formatter) {
let configForFile;
try {
configForFile = await getConfigForFile(stylelint, configPath);
} catch (err) {
if (err instanceof Error && 'code' in err && err.code === constants.EXIT_CODE_INVALID_CONFIG) {
configForFile = undefined;
} else {
throw err;
}
}
formatter = configForFile?.config.formatter;
}
if (typeof formatter === 'string') {
let formatterFunction = index[formatter];
if (formatterFunction === undefined) {
if (fs.existsSync(formatter)) {
formatterFunction = await dynamicImport(path.resolve(formatter)).then((m) => m.default);
} else {
const formattersText = getFormatterOptionsText(', ', '"');
throw new Error(`You must use a valid formatter option: ${formattersText} or a function`);
}
}
return formatterFunction;
}
// Assume a function or a promise of a function.
if (typeof formatter === 'function' || formatter) {
return Promise.resolve(formatter);
}
formatter ??= stylelint._options._defaultFormatter ?? 'json';
return index[formatter];
}
module.exports = getFormatter;