Actualizacion maquina principal
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / prettier-eslint / dist / index.js
1 "use strict";
2
3 require("core-js/modules/es.array.iterator");
4
5 var _fs = _interopRequireDefault(require("fs"));
6
7 var _path = _interopRequireDefault(require("path"));
8
9 var _requireRelative = _interopRequireDefault(require("require-relative"));
10
11 var _prettyFormat = _interopRequireDefault(require("pretty-format"));
12
13 var _commonTags = require("common-tags");
14
15 var _indentString = _interopRequireDefault(require("indent-string"));
16
17 var _loglevelColoredLevelPrefix = _interopRequireDefault(require("loglevel-colored-level-prefix"));
18
19 var _lodash = _interopRequireDefault(require("lodash.merge"));
20
21 var _utils = require("./utils");
22
23 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
24
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; }
26
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; }
28
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; }
30
31 const logger = (0, _loglevelColoredLevelPrefix.default)({
32   prefix: 'prettier-eslint'
33 }); // CommonJS + ES6 modules... is it worth it? Probably not...
34
35 module.exports = format;
36 /**
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
48  *  with ESLint.
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
54  *  eslintConfig.
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
59  */
60
61 function format(options) {
62   const {
63     logLevel = getDefaultLogLevel()
64   } = options;
65   logger.setLevel(logLevel);
66   logger.trace('called format with options:', (0, _prettyFormat.default)(options));
67   const {
68     filePath,
69     text = getTextFromFilePath(filePath),
70     eslintPath = getModulePath(filePath, 'eslint'),
71     prettierPath = getModulePath(filePath, 'prettier'),
72     prettierLast,
73     fallbackPrettierOptions
74   } = options;
75   const eslintConfig = (0, _lodash.default)({}, options.eslintConfig, getESLintConfig(filePath, eslintPath));
76
77   if (typeof eslintConfig.globals === 'object') {
78     eslintConfig.globals = Object.entries(eslintConfig.globals).map(([key, value]) => `${key}:${value}`);
79   }
80
81   const prettierOptions = (0, _lodash.default)({}, filePath && {
82     filepath: 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)({
86     filePath,
87     text,
88     eslintPath,
89     prettierPath,
90     eslintConfig: formattingOptions.eslint,
91     prettierOptions: formattingOptions.prettier,
92     logLevel,
93     prettierLast
94   }));
95   const eslintExtensions = eslintConfig.extensions || ['.js', '.jsx', '.ts', '.tsx', '.mjs', '.vue'];
96
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.
99
100
101   const onlyPrettier = filePath ? !eslintExtensions.includes(fileExtension) : false;
102   const prettify = createPrettify(formattingOptions.prettier, prettierPath);
103
104   if (onlyPrettier) {
105     return prettify(text);
106   }
107
108   if (['.ts', '.tsx'].includes(fileExtension)) {
109     formattingOptions.eslint.parser = formattingOptions.eslint.parser || require.resolve('@typescript-eslint/parser');
110   }
111
112   if (['.vue'].includes(fileExtension)) {
113     formattingOptions.eslint.parser = formattingOptions.eslint.parser || require.resolve('vue-eslint-parser');
114   }
115
116   const eslintFix = createEslintFix(formattingOptions.eslint, eslintPath);
117
118   if (prettierLast) {
119     return prettify(eslintFix(text, filePath));
120   }
121
122   return eslintFix(prettify(text), filePath);
123 }
124
125 function createPrettify(formatOptions, prettierPath) {
126   return function prettify(text) {
127     logger.debug('calling prettier on text');
128     logger.trace((0, _commonTags.stripIndent)`
129       prettier input:
130
131       ${(0, _indentString.default)(text, 2)}
132     `);
133     const prettier = (0, _utils.requireModule)(prettierPath, 'prettier');
134
135     try {
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)`
140         prettier output:
141
142         ${(0, _indentString.default)(output, 2)}
143       `);
144       return output;
145     } catch (error) {
146       logger.error('prettier formatting failed due to a prettier error');
147       throw error;
148     }
149   };
150 }
151
152 function createEslintFix(eslintConfig, eslintPath) {
153   return function eslintFix(text, filePath) {
154     const cliEngine = (0, _utils.getESLintCLIEngine)(eslintPath, eslintConfig);
155
156     try {
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`
161
162       const [{
163         output = text
164       }] = report.results;
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
169
170       logger.trace((0, _commonTags.stripIndent)`
171         eslint --fix output:
172
173         ${(0, _indentString.default)(output, 2)}
174       `);
175       return output;
176     } catch (error) {
177       logger.error('eslint fix failed due to an eslint error');
178       throw error;
179     }
180   };
181 }
182
183 function getTextFromFilePath(filePath) {
184   try {
185     logger.trace((0, _commonTags.oneLine)`
186         attempting fs.readFileSync to get
187         the text for file at "${filePath}"
188       `);
189     return _fs.default.readFileSync(filePath, 'utf8');
190   } catch (error) {
191     logger.error((0, _commonTags.oneLine)`
192         failed to get the text to format
193         from the given filePath: "${filePath}"
194       `);
195     throw error;
196   }
197 }
198
199 function getESLintConfig(filePath, eslintPath) {
200   const eslintOptions = {};
201
202   if (filePath) {
203     eslintOptions.cwd = _path.default.dirname(filePath);
204   }
205
206   logger.trace((0, _commonTags.oneLine)`
207       creating ESLint CLI Engine to get the config for
208       "${filePath || process.cwd()}"
209     `);
210   const cliEngine = (0, _utils.getESLintCLIEngine)(eslintPath, eslintOptions);
211
212   try {
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);
217   } catch (error) {
218     // is this noisy? Try setting options.disableLog to false
219     logger.debug('Unable to find config');
220     return {
221       rules: {}
222     };
223   }
224 }
225
226 function getPrettierConfig(filePath, prettierPath) {
227   const prettier = (0, _utils.requireModule)(prettierPath, 'prettier');
228   return prettier.resolveConfig && prettier.resolveConfig.sync && prettier.resolveConfig.sync(filePath) || {};
229 }
230
231 function getModulePath(filePath = __filename, moduleName) {
232   try {
233     return _requireRelative.default.resolve(moduleName, filePath);
234   } catch (error) {
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);
240   }
241 }
242
243 function getDefaultLogLevel() {
244   return process.env.LOG_LEVEL || 'warn';
245 }