forked from prettier/eslint-plugin-prettier
-
Notifications
You must be signed in to change notification settings - Fork 0
/
eslint-plugin-prettier.js
227 lines (201 loc) · 7.2 KB
/
eslint-plugin-prettier.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
/**
* @file Runs `prettier` as an ESLint rule.
* @author Andres Suarez
*/
// @ts-check
/**
* @typedef {import('eslint').AST.Range} Range
* @typedef {import('eslint').AST.SourceLocation} SourceLocation
* @typedef {import('eslint').ESLint.Plugin} Plugin
* @typedef {import('prettier').FileInfoOptions} FileInfoOptions
* @typedef {import('prettier').Options & { onDiskFilepath: string, parserPath: string, usePrettierrc?: boolean }} Options
*/
'use strict';
// ------------------------------------------------------------------------------
// Requirements
// ------------------------------------------------------------------------------
const {
showInvisibles,
generateDifferences,
} = require('prettier-linter-helpers');
// ------------------------------------------------------------------------------
// Constants
// ------------------------------------------------------------------------------
const { INSERT, DELETE, REPLACE } = generateDifferences;
// ------------------------------------------------------------------------------
// Privates
// ------------------------------------------------------------------------------
// Lazily-loaded Prettier.
/**
* @type {(source: string, options: Options, fileInfoOptions: FileInfoOptions) => string}
*/
let prettierFormat;
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
/**
* Reports a difference.
*
* @param {import('eslint').Rule.RuleContext} context - The ESLint rule context.
* @param {import('prettier-linter-helpers').Difference} difference - The difference object.
* @returns {void}
*/
function reportDifference(context, difference) {
const { operation, offset, deleteText = '', insertText = '' } = difference;
const range = /** @type {Range} */ ([offset, offset + deleteText.length]);
const [start, end] = range.map(index =>
context.getSourceCode().getLocFromIndex(index),
);
context.report({
messageId: operation,
data: {
deleteText: showInvisibles(deleteText),
insertText: showInvisibles(insertText),
},
loc: { start, end },
fix: fixer => fixer.replaceTextRange(range, insertText),
});
}
// ------------------------------------------------------------------------------
// Module Definition
// ------------------------------------------------------------------------------
/**
* @type {Plugin}
*/
const eslintPluginPrettier = {
configs: {
recommended: {
extends: ['prettier'],
plugins: ['prettier'],
rules: {
'prettier/prettier': 'error',
'arrow-body-style': 'off',
'prefer-arrow-callback': 'off',
},
},
},
rules: {
prettier: {
meta: {
docs: {
url: 'https://github.com/prettier/eslint-plugin-prettier#options',
},
type: 'layout',
fixable: 'code',
schema: [
// Prettier options:
{
type: 'object',
properties: {},
additionalProperties: true,
},
{
type: 'object',
properties: {
usePrettierrc: { type: 'boolean' },
fileInfoOptions: {
type: 'object',
properties: {},
additionalProperties: true,
},
},
additionalProperties: true,
},
],
messages: {
[INSERT]: 'Insert `{{ insertText }}`',
[DELETE]: 'Delete `{{ deleteText }}`',
[REPLACE]: 'Replace `{{ deleteText }}` with `{{ insertText }}`',
},
},
create(context) {
const usePrettierrc =
!context.options[1] || context.options[1].usePrettierrc !== false;
/**
* @type {FileInfoOptions}
*/
const fileInfoOptions =
(context.options[1] && context.options[1].fileInfoOptions) || {};
const sourceCode = context.getSourceCode();
const filepath = context.getFilename();
// Processors that extract content from a file, such as the markdown
// plugin extracting fenced code blocks may choose to specify virtual
// file paths. If this is the case then we need to resolve prettier
// config and file info using the on-disk path instead of the virtual
// path.
const onDiskFilepath = context.getPhysicalFilename();
const source = sourceCode.text;
return {
Program() {
if (!prettierFormat) {
// Prettier is expensive to load, so only load it if needed.
prettierFormat = require('synckit').createSyncFn(
require.resolve('./worker'),
);
}
/**
* @type {{}}
*/
const eslintPrettierOptions = context.options[0] || {};
// prettier.format() may throw a SyntaxError if it cannot parse the
// source code it is given. Usually for JS files this isn't a
// problem as ESLint will report invalid syntax before trying to
// pass it to the prettier plugin. However this might be a problem
// for non-JS languages that are handled by a plugin. Notably Vue
// files throw an error if they contain unclosed elements, such as
// `<template><div></template>. In this case report an error at the
// point at which parsing failed.
/**
* @type {string}
*/
let prettierSource;
try {
prettierSource = prettierFormat(
source,
{
...eslintPrettierOptions,
filepath,
onDiskFilepath,
parserPath: context.parserPath,
usePrettierrc,
},
fileInfoOptions,
);
} catch (err) {
if (!(err instanceof SyntaxError)) {
throw err;
}
let message = 'Parsing error: ' + err.message;
const error =
/** @type {SyntaxError & {codeFrame: string; loc: SourceLocation}} */ (
err
);
// Prettier's message contains a codeframe style preview of the
// invalid code and the line/column at which the error occurred.
// ESLint shows those pieces of information elsewhere already so
// remove them from the message
if (error.codeFrame) {
message = message.replace(`\n${error.codeFrame}`, '');
}
if (error.loc) {
message = message.replace(/ \(\d+:\d+\)$/, '');
}
context.report({ message, loc: error.loc });
return;
}
if (prettierSource == null) {
return;
}
if (source !== prettierSource) {
const differences = generateDifferences(source, prettierSource);
for (const difference of differences) {
reportDifference(context, difference);
}
}
},
};
},
},
},
};
module.exports = eslintPluginPrettier;