-
-
Notifications
You must be signed in to change notification settings - Fork 448
/
PrettierEditProvider.ts
236 lines (211 loc) · 7.19 KB
/
PrettierEditProvider.ts
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
import {
DocumentRangeFormattingEditProvider,
DocumentFormattingEditProvider,
Range,
TextDocument,
FormattingOptions,
CancellationToken,
TextEdit,
} from 'vscode';
import { safeExecution, addToOutput, setUsedModule } from './errorHandler';
import { getGroup, getParsersFromLanguageId, getConfig } from './utils';
import { requireLocalPkg } from './requirePkg';
import {
PrettierVSCodeConfig,
Prettier,
PrettierEslintFormat,
ParserOption,
PrettierStylelint,
PrettierConfig,
} from './types.d';
const bundledPrettier = require('prettier') as Prettier;
/**
* HOLD style parsers (for stylelint integration)
*/
const STYLE_PARSERS: ParserOption[] = ['postcss', 'css', 'less', 'scss'];
/**
* Check if a given file has an associated prettierconfig.
* @param filePath file's path
*/
async function hasPrettierConfig(filePath: string) {
return (await bundledPrettier.resolveConfig(filePath)) !== null;
}
/**
* Define which config should be used.
* If a prettierconfig exists, it returns itself.
* It merges prettierconfig into vscode's config (editorconfig).
* Priority:
* - additionalConfig
* - prettierConfig
* - vscodeConfig
* @param hasPrettierConfig a prettierconfig exists
* @param additionalConfig config we really want to see in. (range)
* @param prettierConfig prettier's file config
* @param vscodeConfig our config
*/
function mergeConfig(
hasPrettierConfig: boolean,
additionalConfig: Partial<PrettierConfig>,
prettierConfig: Partial<PrettierConfig>,
vscodeConfig: Partial<PrettierConfig>
) {
return hasPrettierConfig
? Object.assign(
{ parser: vscodeConfig.parser }, // always merge our inferred parser in
prettierConfig,
additionalConfig
)
: Object.assign(vscodeConfig, prettierConfig, additionalConfig);
}
/**
* Format the given text with user's configuration.
* @param text Text to format
* @param path formatting file's path
* @returns {string} formatted text
*/
async function format(
text: string,
{ fileName, languageId, uri }: TextDocument,
customOptions: Partial<PrettierConfig>
): Promise<string> {
const vscodeConfig: PrettierVSCodeConfig = getConfig(uri);
const localPrettier = requireLocalPkg(fileName, 'prettier') as Prettier;
// This has to stay, as it allows to skip in sub workspaceFolders. Sadly noop.
// wf1 (with "lang") -> glob: "wf1/**"
// wf1/wf2 (without "lang") -> match "wf1/**"
if (vscodeConfig.disableLanguages.includes(languageId)) {
return text;
}
const dynamicParsers = getParsersFromLanguageId(
languageId,
localPrettier.version
);
let useBundled = false;
let parser: ParserOption;
if (!dynamicParsers.length) {
const bundledParsers = getParsersFromLanguageId(
languageId,
bundledPrettier.version
);
parser = bundledParsers[0] || 'babylon';
useBundled = true;
} else if (dynamicParsers.includes(vscodeConfig.parser)) {
// handle deprecated parser option (parser: "flow")
parser = vscodeConfig.parser;
} else {
parser = dynamicParsers[0];
}
const doesParserSupportEslint = getGroup('JavaScript').some(lang =>
lang.parsers.includes(parser)
);
const hasConfig = await hasPrettierConfig(fileName);
if (!hasConfig && vscodeConfig.requireConfig) {
return text;
}
const fileOptions = await bundledPrettier.resolveConfig(fileName, {
editorconfig: true,
});
const prettierOptions = mergeConfig(hasConfig, customOptions, fileOptions, {
printWidth: vscodeConfig.printWidth,
tabWidth: vscodeConfig.tabWidth,
singleQuote: vscodeConfig.singleQuote,
trailingComma: vscodeConfig.trailingComma,
bracketSpacing: vscodeConfig.bracketSpacing,
jsxBracketSameLine: vscodeConfig.jsxBracketSameLine,
parser: parser,
semi: vscodeConfig.semi,
useTabs: vscodeConfig.useTabs,
proseWrap: vscodeConfig.proseWrap,
arrowParens: vscodeConfig.arrowParens,
});
if (vscodeConfig.eslintIntegration && doesParserSupportEslint) {
return safeExecution(
() => {
const prettierEslint = require('prettier-eslint') as PrettierEslintFormat;
setUsedModule('prettier-eslint', 'Unknown', true);
return prettierEslint({
text,
filePath: fileName,
fallbackPrettierOptions: prettierOptions,
});
},
text,
fileName
);
}
if (vscodeConfig.stylelintIntegration && STYLE_PARSERS.includes(parser)) {
const prettierStylelint = require('prettier-stylelint') as PrettierStylelint;
return safeExecution(
prettierStylelint.format({
text,
filePath: fileName,
prettierOptions,
}),
text,
fileName
);
}
if (!doesParserSupportEslint && useBundled) {
return safeExecution(
() => {
const warningMessage =
`prettier@${
localPrettier.version
} doesn't support ${languageId}. ` +
`Falling back to bundled prettier@${
bundledPrettier.version
}.`;
addToOutput(warningMessage);
setUsedModule('prettier', bundledPrettier.version, true);
return bundledPrettier.format(text, prettierOptions);
},
text,
fileName
);
}
setUsedModule('prettier', localPrettier.version, false);
return safeExecution(
() => localPrettier.format(text, prettierOptions),
text,
fileName
);
}
function fullDocumentRange(document: TextDocument): Range {
const lastLineId = document.lineCount - 1;
return new Range(0, 0, lastLineId, document.lineAt(lastLineId).text.length);
}
class PrettierEditProvider
implements DocumentRangeFormattingEditProvider,
DocumentFormattingEditProvider {
constructor(private _fileIsIgnored: (filePath: string) => boolean) {}
provideDocumentRangeFormattingEdits(
document: TextDocument,
range: Range,
options: FormattingOptions,
token: CancellationToken
): Promise<TextEdit[]> {
return this._provideEdits(document, {
rangeStart: document.offsetAt(range.start),
rangeEnd: document.offsetAt(range.end),
});
}
provideDocumentFormattingEdits(
document: TextDocument,
options: FormattingOptions,
token: CancellationToken
): Promise<TextEdit[]> {
return this._provideEdits(document, {});
}
private _provideEdits(
document: TextDocument,
options: Partial<PrettierConfig>
) {
if (!document.isUntitled && this._fileIsIgnored(document.fileName)) {
return Promise.resolve([]);
}
return format(document.getText(), document, options).then(code => [
TextEdit.replace(fullDocumentRange(document), code),
]);
}
}
export default PrettierEditProvider;