/
index.js
247 lines (227 loc) · 7.19 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
/* eslint no-console:0, global-require:0, import/no-dynamic-require:0 */
import fs from 'fs'
import path from 'path'
import requireRelative from 'require-relative'
import prettyFormat from 'pretty-format'
import {oneLine, stripIndent} from 'common-tags'
import indentString from 'indent-string'
import getLogger from 'loglevel-colored-level-prefix'
import {getOptionsForFormatting, defaultEslintConfig} from './utils'
const logger = getLogger({prefix: 'prettier-eslint'})
// CommonJS + ES6 modules... is it worth it? Probably not...
module.exports = format
/**
* Formats the text with prettier and then eslint based on the given options
* @param {String} options.filePath - the path of the file being formatted
* can be used in leu of `eslintConfig` (eslint will be used to find the
* relevant config for the file). Will also be used to load the `text` if
* `text` is not provided.
* @param {String} options.text - the text (JavaScript code) to format
* @param {String} options.eslintPath - the path to the eslint module to use.
* Will default to require.resolve('eslint')
* @param {String} options.prettierPath - the path to the prettier module.
* Will default to require.resovlve('prettierPath')
* @param {String} options.eslintConfig - the config to use for formatting
* with ESLint.
* @param {Object} options.prettierOptions - the options to pass for
* formatting with `prettier`. If not provided, prettier-eslint will attempt
* to create the options based on the eslintConfig
* @param {Object} options.fallbackPrettierOptions - the options to pass for
* formatting with `prettier` if the given option is not inferrable from the
* eslintConfig.
* @param {String} options.logLevel - the level for the logs
* (error, warn, info, debug, trace)
* @param {Boolean} options.prettierLast - Run Prettier Last
* @return {String} - the formatted string
*/
function format(options) {
const {logLevel = getDefaultLogLevel()} = options
logger.setLevel(logLevel)
logger.trace('called format with options:', prettyFormat(options))
const {
filePath,
text = getTextFromFilePath(filePath),
eslintPath = getModulePath(filePath, 'eslint'),
prettierPath = getModulePath(filePath, 'prettier'),
prettierOptions,
prettierLast,
fallbackPrettierOptions,
} = options
const eslintConfig = defaultEslintConfig(
getConfig(filePath, eslintPath),
options.eslintConfig,
)
const formattingOptions = getOptionsForFormatting(
eslintConfig,
prettierOptions,
fallbackPrettierOptions,
)
logger.debug(
'inferred options:',
prettyFormat({
filePath,
text,
eslintPath,
prettierPath,
eslintConfig: formattingOptions.eslint,
prettierOptions: formattingOptions.prettier,
logLevel,
prettierLast,
}),
)
const prettify = createPrettify(formattingOptions.prettier, prettierPath)
const eslintFix = createEslintFix(formattingOptions.eslint, eslintPath)
if (prettierLast) {
return prettify(eslintFix(text, filePath))
}
return eslintFix(prettify(text), filePath)
}
function createPrettify(formatOptions, prettierPath) {
return function prettify(text) {
logger.debug('calling prettier on text')
logger.trace(
stripIndent`
prettier input:
${indentString(text, 2)}
`,
)
let prettier
try {
logger.trace(`requiring prettier module at "${prettierPath}"`)
prettier = require(prettierPath)
} catch (error) {
logger.error(
oneLine`
There was trouble getting prettier.
Is "prettierPath: ${prettierPath}"
a correct path to the prettier module?
`,
)
throw error
}
try {
logger.trace(`calling prettier.format with the text and prettierOptions`)
const output = prettier.format(text, formatOptions)
logger.trace('prettier: output === input', output === text)
logger.trace(
stripIndent`
prettier output:
${indentString(output, 2)}
`,
)
return output
} catch (error) {
logger.error('prettier formatting failed due to a prettier error')
throw error
}
}
}
function createEslintFix(eslintConfig, eslintPath) {
return function eslintFix(text, filePath) {
const eslint = getESLintCLIEngine(eslintPath, eslintConfig)
try {
logger.trace(`calling eslint.executeOnText with the text`)
const report = eslint.executeOnText(text, filePath, true)
logger.trace(
`executeOnText returned the following report:`,
prettyFormat(report),
)
// default the output to text because if there's nothing
// to fix, eslint doesn't provide `output`
const [{output = text}] = report.results
logger.trace('eslint --fix: output === input', output === text)
// NOTE: We're ignoring linting errors/warnings here and
// defaulting to the given text if there are any
// because all we're trying to do is fix what we can.
// We don't care about what we can't
logger.trace(
stripIndent`
eslint --fix output:
${indentString(output, 2)}
`,
)
return output
} catch (error) {
logger.error('eslint fix failed due to an eslint error')
throw error
}
}
}
function getTextFromFilePath(filePath) {
try {
logger.trace(
oneLine`
attempting fs.readFileSync to get
the text for file at "${filePath}"
`,
)
return fs.readFileSync(filePath, 'utf8')
} catch (error) {
logger.error(
oneLine`
failed to get the text to format
from the given filePath: "${filePath}"
`,
)
throw error
}
}
function getConfig(filePath, eslintPath) {
const eslintOptions = {}
if (filePath) {
eslintOptions.cwd = path.dirname(filePath)
}
logger.trace(
oneLine`
creating ESLint CLI Engine to get the config for
"${filePath || process.cwd()}"
`,
)
const configFinder = getESLintCLIEngine(eslintPath, eslintOptions)
try {
logger.debug(`getting eslint config for file at "${filePath}"`)
const config = configFinder.getConfigForFile(filePath)
logger.trace(
`eslint config for "${filePath}" received`,
prettyFormat(config),
)
return config
} catch (error) {
// is this noisy? Try setting options.disableLog to false
logger.debug('Unable to find config')
return {rules: {}}
}
}
function getModulePath(filePath = __filename, moduleName) {
try {
return requireRelative.resolve(moduleName, filePath)
} catch (error) {
logger.debug(
oneLine`
There was a problem finding the ${moduleName}
module. Using prettier-eslint's version.
`,
error.message,
error.stack,
)
return require.resolve(moduleName)
}
}
function getESLintCLIEngine(eslintPath, eslintOptions) {
try {
logger.trace(`requiring eslint module at "${eslintPath}"`)
const {CLIEngine} = require(eslintPath)
return new CLIEngine(eslintOptions)
} catch (error) {
logger.error(
oneLine`
There was trouble creating the ESLint CLIEngine.
Is "eslintPath: ${eslintPath}" a correct path to the ESLint module?
`,
)
throw error
}
}
function getDefaultLogLevel() {
return process.env.LOG_LEVEL || 'warn'
}