3 require("core-js/modules/es.array.iterator");
5 var _fs = _interopRequireDefault(require("fs"));
7 var _path = _interopRequireDefault(require("path"));
9 var _requireRelative = _interopRequireDefault(require("require-relative"));
11 var _prettyFormat = _interopRequireDefault(require("pretty-format"));
13 var _commonTags = require("common-tags");
15 var _indentString = _interopRequireDefault(require("indent-string"));
17 var _loglevelColoredLevelPrefix = _interopRequireDefault(require("loglevel-colored-level-prefix"));
19 var _lodash = _interopRequireDefault(require("lodash.merge"));
21 var _utils = require("./utils");
23 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
25 function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
27 function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
29 function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
31 const logger = (0, _loglevelColoredLevelPrefix.default)({
32 prefix: 'prettier-eslint'
33 }); // CommonJS + ES6 modules... is it worth it? Probably not...
35 module.exports = format;
37 * Formats the text with prettier and then eslint based on the given options
38 * @param {String} options.filePath - the path of the file being formatted
39 * can be used in leu of `eslintConfig` (eslint will be used to find the
40 * relevant config for the file). Will also be used to load the `text` if
41 * `text` is not provided.
42 * @param {String} options.text - the text (JavaScript code) to format
43 * @param {String} options.eslintPath - the path to the eslint module to use.
44 * Will default to require.resolve('eslint')
45 * @param {String} options.prettierPath - the path to the prettier module.
46 * Will default to require.resovlve('prettier')
47 * @param {Object} options.eslintConfig - the config to use for formatting
49 * @param {Object} options.prettierOptions - the options to pass for
50 * formatting with `prettier`. If not provided, prettier-eslint will attempt
51 * to create the options based on the eslintConfig
52 * @param {Object} options.fallbackPrettierOptions - the options to pass for
53 * formatting with `prettier` if the given option is not inferrable from the
55 * @param {String} options.logLevel - the level for the logs
56 * (error, warn, info, debug, trace)
57 * @param {Boolean} options.prettierLast - Run Prettier Last
58 * @return {String} - the formatted string
61 function format(options) {
63 logLevel = getDefaultLogLevel()
65 logger.setLevel(logLevel);
66 logger.trace('called format with options:', (0, _prettyFormat.default)(options));
69 text = getTextFromFilePath(filePath),
70 eslintPath = getModulePath(filePath, 'eslint'),
71 prettierPath = getModulePath(filePath, 'prettier'),
73 fallbackPrettierOptions
75 const eslintConfig = (0, _lodash.default)({}, options.eslintConfig, getESLintConfig(filePath, eslintPath));
77 if (typeof eslintConfig.globals === 'object') {
78 eslintConfig.globals = Object.entries(eslintConfig.globals).map(([key, value]) => `${key}:${value}`);
81 const prettierOptions = (0, _lodash.default)({}, filePath && {
83 }, getPrettierConfig(filePath, prettierPath), options.prettierOptions);
84 const formattingOptions = (0, _utils.getOptionsForFormatting)(eslintConfig, prettierOptions, fallbackPrettierOptions, eslintPath);
85 logger.debug('inferred options:', (0, _prettyFormat.default)({
90 eslintConfig: formattingOptions.eslint,
91 prettierOptions: formattingOptions.prettier,
95 const eslintExtensions = eslintConfig.extensions || ['.js', '.jsx', '.ts', '.tsx', '.mjs', '.vue'];
97 const fileExtension = _path.default.extname(filePath || ''); // If we don't get filePath run eslint on text, otherwise only run eslint
98 // if it's a configured extension or fall back to a "supported" file type.
101 const onlyPrettier = filePath ? !eslintExtensions.includes(fileExtension) : false;
102 const prettify = createPrettify(formattingOptions.prettier, prettierPath);
105 return prettify(text);
108 if (['.ts', '.tsx'].includes(fileExtension)) {
109 formattingOptions.eslint.parser = formattingOptions.eslint.parser || require.resolve('@typescript-eslint/parser');
112 if (['.vue'].includes(fileExtension)) {
113 formattingOptions.eslint.parser = formattingOptions.eslint.parser || require.resolve('vue-eslint-parser');
116 const eslintFix = createEslintFix(formattingOptions.eslint, eslintPath);
119 return prettify(eslintFix(text, filePath));
122 return eslintFix(prettify(text), filePath);
125 function createPrettify(formatOptions, prettierPath) {
126 return function prettify(text) {
127 logger.debug('calling prettier on text');
128 logger.trace((0, _commonTags.stripIndent)`
131 ${(0, _indentString.default)(text, 2)}
133 const prettier = (0, _utils.requireModule)(prettierPath, 'prettier');
136 logger.trace(`calling prettier.format with the text and prettierOptions`);
137 const output = prettier.format(text, formatOptions);
138 logger.trace('prettier: output === input', output === text);
139 logger.trace((0, _commonTags.stripIndent)`
142 ${(0, _indentString.default)(output, 2)}
146 logger.error('prettier formatting failed due to a prettier error');
152 function createEslintFix(eslintConfig, eslintPath) {
153 return function eslintFix(text, filePath) {
154 const cliEngine = (0, _utils.getESLintCLIEngine)(eslintPath, eslintConfig);
157 logger.trace(`calling cliEngine.executeOnText with the text`);
158 const report = cliEngine.executeOnText(text, filePath, true);
159 logger.trace(`executeOnText returned the following report:`, (0, _prettyFormat.default)(report)); // default the output to text because if there's nothing
160 // to fix, eslint doesn't provide `output`
165 logger.trace('eslint --fix: output === input', output === text); // NOTE: We're ignoring linting errors/warnings here and
166 // defaulting to the given text if there are any
167 // because all we're trying to do is fix what we can.
168 // We don't care about what we can't
170 logger.trace((0, _commonTags.stripIndent)`
173 ${(0, _indentString.default)(output, 2)}
177 logger.error('eslint fix failed due to an eslint error');
183 function getTextFromFilePath(filePath) {
185 logger.trace((0, _commonTags.oneLine)`
186 attempting fs.readFileSync to get
187 the text for file at "${filePath}"
189 return _fs.default.readFileSync(filePath, 'utf8');
191 logger.error((0, _commonTags.oneLine)`
192 failed to get the text to format
193 from the given filePath: "${filePath}"
199 function getESLintConfig(filePath, eslintPath) {
200 const eslintOptions = {};
203 eslintOptions.cwd = _path.default.dirname(filePath);
206 logger.trace((0, _commonTags.oneLine)`
207 creating ESLint CLI Engine to get the config for
208 "${filePath || process.cwd()}"
210 const cliEngine = (0, _utils.getESLintCLIEngine)(eslintPath, eslintOptions);
213 logger.debug(`getting eslint config for file at "${filePath}"`);
214 const config = cliEngine.getConfigForFile(filePath);
215 logger.trace(`eslint config for "${filePath}" received`, (0, _prettyFormat.default)(config));
216 return _objectSpread(_objectSpread({}, eslintOptions), config);
218 // is this noisy? Try setting options.disableLog to false
219 logger.debug('Unable to find config');
226 function getPrettierConfig(filePath, prettierPath) {
227 const prettier = (0, _utils.requireModule)(prettierPath, 'prettier');
228 return prettier.resolveConfig && prettier.resolveConfig.sync && prettier.resolveConfig.sync(filePath) || {};
231 function getModulePath(filePath = __filename, moduleName) {
233 return _requireRelative.default.resolve(moduleName, filePath);
235 logger.debug((0, _commonTags.oneLine)`
236 There was a problem finding the ${moduleName}
237 module. Using prettier-eslint's version.
238 `, error.message, error.stack);
239 return require.resolve(moduleName);
243 function getDefaultLogLevel() {
244 return process.env.LOG_LEVEL || 'warn';