forked from jscheid/prettier.el
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprettier-el.js
614 lines (553 loc) · 16.1 KB
/
prettier-el.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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
/**
* @fileoverview prettier.el main server process
*/
// Copyright (c) 2018-present Julian Scheid
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// Hack to circumvent Closure Compiler CommonJS resolution
const externalRequire = require;
const fs = externalRequire("fs");
const path = externalRequire("path");
const vm = externalRequire("vm");
const punycode = externalRequire("punycode");
const execSync = externalRequire("child_process")["execSync"];
// We return this exit code whenever there's unexpected data on the wire
const EXIT_CODE_PROTOCOL_ERROR = 1;
// Keep track of loaded Prettier instances by file path.
const prettierCache = new Map();
const Z = createResponseHeader("Z", 0);
const newline = Buffer.from("\n");
const otherParserName = new Map([
["babylon", "babel"],
["babel", "babylon"],
]);
/** @type{PrettierAPI} */
let globalPrettier;
/**
* Slurp the given number of bytes from the given file descriptor, return a
* buffer.
*
* @param {!number} fd File descriptor to read from.
* @param {!number} numBytes Number of bytes to read.
*
* @return {!Buffer} The data read.
*/
function readFully(fd, numBytes) {
const buf = Buffer.alloc(numBytes);
let offset = 0;
while (offset < numBytes) {
const numRead = fs["readSync"](fd, buf, offset, numBytes - offset, null);
if (numRead <= 0) {
throw new Error("EOF");
}
offset += numRead;
}
return buf;
}
/**
* Bail out when a protocol error occurs.
*/
function protocolError() {
process.exit(EXIT_CODE_PROTOCOL_ERROR);
}
/**
* @param{!string} chr
* @param{!number} val
* @return{!Buffer}
*/
function createResponseHeader(chr, val) {
return Buffer.from(chr + val.toString(16) + "\n");
}
/**
* Return a Buffer containing the given string encoded as Base64, split into
* chunks to ensure no line is too long.
*
* @param{!string} str
* @return{!Buffer}
*/
function createBase64Buffer(str) {
return Buffer.from(
Buffer.from(str)
.toString("base64")
.match(/.{1,64}/g)
.join("\n")
.trim()
);
}
/**
* Return a Buffer containing the given number as an unsigned 32-bit integer,
* little-endian encoded.
*
* @param{!number} val
* @return{!Buffer}
*/
function makeU32(val) {
const buf = Buffer.alloc(4);
buf.writeUInt32LE(val, 0);
return buf;
}
/**
* Find a globally installed Prettier. Throw if not found. Memoize results for
* future lookups.
*
* @return {!PrettierAPI}
*/
function getGlobalPrettier() {
if (globalPrettier) {
return globalPrettier;
}
let npmGlobalPath;
let yarnGlobalPath;
const execSyncOptions = {
["encoding"]: "utf-8",
["stdio"]: ["ignore", "pipe", "ignore"],
};
try {
npmGlobalPath = path["join"](
execSync("npm root -g", execSyncOptions).trim(),
"prettier"
);
} catch (e) {
// ignore
}
try {
yarnGlobalPath = path["join"](
execSync("yarn global dir", execSyncOptions).trim(),
"node_modules",
"prettier"
);
} catch (e) {
// ignore
}
const pathOptions = ["prettier", npmGlobalPath, yarnGlobalPath];
for (let i = 0; i < pathOptions.length; ++i) {
if (pathOptions[i]) {
try {
globalPrettier = externalRequire(pathOptions[i]);
break;
} catch (e) {
if (!(e instanceof Error) || e["code"] !== "MODULE_NOT_FOUND") {
throw e;
}
}
}
}
if (globalPrettier) {
return globalPrettier;
} else {
throw new Error("Cannot find prettier anywhere");
}
}
/**
* Return the Prettier package from `node_modules` if it exists.
*
* @param {!string} directory
* @return {!PrettierAPI|null}
*/
function getLocalPrettier(directory) {
const prettierCandidate = path["join"](directory, "node_modules", "prettier");
try {
const stat = fs["statSync"](prettierCandidate);
return stat.isDirectory() ? externalRequire(prettierCandidate) : null;
} catch (e) {
if (e.code === "ENOENT") return null;
throw e;
}
}
/**
* Return the Prettier package under Yarn Plug'n'Play if either `.pnp.js` or
* `.pnp.cjs` exists. Inject PnP API into the Node.js environment only once.
* This side effect is unlikely to be a problem at present but we recommend to
* use project-specific Node.js executable with any tool such as `direnv`.
*
* @param {!string} directory
* @return {!PrettierAPI|null}
*/
function getYarnPnpifyedLocalPrettier(directory) {
const yarnPnpCandidate = path["join"](directory, ".pnp");
if (
fs["existsSync"](yarnPnpCandidate + ".js") ||
fs["existsSync"](yarnPnpCandidate + ".cjs")
) {
try {
const m = externalRequire("module");
const createRequire = m["createRequire"] || m["createRequireFromPath"];
if (!createRequire) {
throw new Error("You should upgrage Node.js v10.12.0 or above.");
}
if (!process["versions"]["pnp"]) {
externalRequire(yarnPnpCandidate)["setup"]();
}
const targetRequire = createRequire(yarnPnpCandidate);
return targetRequire(targetRequire["resolve"]("prettier"));
} catch (e) {
if (e.code === "ENOENT") return null;
throw e;
}
}
return null;
}
/**
* Find the Prettier package to use for the given directory, falling back to a
* global package. Throw if neither is found. Memoize results for future
* lookups.
*
* @param {!string} directory The directory for which to find the Prettier
* package.
*
* @return {!PrettierAPI} The Prettier package found.
*/
function getPrettierForDirectory(directory) {
const cached = prettierCache.get(directory);
if (cached) return cached;
if (fs["existsSync"](path["join"](directory, "package.json"))) {
const prettier =
getLocalPrettier(directory) || getYarnPnpifyedLocalPrettier(directory);
if (prettier) {
prettierCache.set(directory, prettier);
return prettier;
}
}
const parent = path["dirname"](directory);
if (parent !== directory) {
return getPrettierForDirectory(parent);
} else {
const prettier = getGlobalPrettier();
prettierCache.set(directory, prettier);
return prettier;
}
}
/**
* Find the Prettier package to use for the given file, falling back
* to a global package. Throw if neither is found. Memoize results
* for future lookups.
*
* @param {!string} filepath
*
* @return {!PrettierAPI} The Prettier package found.
*/
function getPrettierForPath(filepath) {
if (!path["isAbsolute"](filepath)) {
return getGlobalPrettier();
}
let prettierPath = prettierCache.get(filepath);
if (!prettierPath) {
const directory = path["dirname"](filepath);
prettierPath = getPrettierForDirectory(directory);
prettierCache.set(filepath, prettierPath);
}
return prettierPath;
}
function parseParsers(parsersString) {
return parsersString === "-"
? null
: parsersString
.split(",")
.reduce(
(accu, parser) =>
accu.concat(parser === "babel" ? ["babel", "babylon"] : [parser]),
[]
);
}
function bestParser(prettier, parsers, options, filepath) {
if (parsers !== null) {
const supportedParsers = prettier.getSupportInfo
? prettier
.getSupportInfo()
["languages"].reduce((accu, lang) => accu.concat(lang["parsers"]), [])
: [];
const result = parsers.find((parser) => supportedParsers.includes(parser));
if (result) {
return result;
}
}
if (filepath) {
return prettier["getFileInfo"].sync(filepath, null)["inferredParser"];
}
return null;
}
/** @suppress {uselessCode} */ (baseScript, cacheFilename, inp) => {
const diff = require("./node_modules/diff-match-patch/index.js");
/**
* Write an error response item.
*
* @param {!Error} err
*/
function writeError(err) {
const errBuf = createBase64Buffer(err.toString());
process.stdout.write(
Buffer.concat([
createResponseHeader("E", errBuf.length),
errBuf,
newline,
Z,
])
);
}
/**
* Handle a request to warm up the engines for a given file.
*
* @param {!Buffer} packet
*/
function handleWarmup(packet) {
try {
const newlineIndex1 = packet.indexOf(10);
if (newlineIndex1 < 0) {
protocolError();
}
const editorconfig = packet[1] === "E".charCodeAt(0);
const filepath = packet.toString("utf-8", 2, newlineIndex1);
const prettier = getPrettierForPath(filepath);
if (filepath.length > 0) {
prettier.resolveConfig.sync(filepath, {
editorconfig,
});
}
} catch (e) {
// ignore this -- the client isn't waiting for our response and
// we have nowhere else to report it.
}
}
/**
* Handle a request for formatting a file.
*
* @param {!Buffer} packet
*/
function handleFormat(packet) {
const editorconfig = packet[1] === "E".charCodeAt(0);
const inferParser = packet[2] === "I".charCodeAt(0);
const newlineIndex1 = packet.indexOf(10);
if (newlineIndex1 < 0) {
protocolError();
}
const filepath = packet.toString("utf-8", 3, newlineIndex1);
const newlineIndex2 = packet.indexOf(10, newlineIndex1 + 1);
if (newlineIndex2 < 0) {
protocolError();
}
const parsersString = packet.toString(
"utf-8",
newlineIndex1 + 1,
newlineIndex2
);
const newlineIndex3 = packet.indexOf(10, newlineIndex2 + 1);
if (newlineIndex3 < 0) {
protocolError();
}
const cursorOffset = parseInt(
packet.toString("ascii", newlineIndex2 + 1, newlineIndex3),
16
);
const filename = packet
.slice(newlineIndex3 + 1, packet.length - 2)
.toString("ascii");
const body = fs["readFileSync"](filename, "utf8");
try {
const prettier = getPrettierForPath(filepath);
const timeBeforeFormat = Date.now();
let options = {};
if (path["isAbsolute"](filepath)) {
options =
prettier.resolveConfig.sync(filepath, {
editorconfig,
}) || {};
}
const parsers = parseParsers(parsersString);
const parser = bestParser(
prettier,
parsers,
options,
inferParser ? filepath : null
);
const out = [];
const prettierVersion = createBase64Buffer(prettier.version);
const parserBuf = createBase64Buffer(parser || "none");
out.push(createResponseHeader("P", parserBuf.length), parserBuf, newline);
out.push(
createResponseHeader("V", prettierVersion.length),
prettierVersion,
newline
);
if (inferParser && !parser) {
out.push(Z);
process.stdout.write(Buffer.concat(out));
return;
}
options["cursorOffset"] = cursorOffset;
options["filepath"] = filepath;
options["rangeStart"] = undefined;
options["rangeEnd"] = undefined;
options["parser"] = parser;
const result = prettier.formatWithCursor(body, options);
const timeAfterFormat = Date.now();
const diffResult = new diff().diff_main(body, result["formatted"]);
for (let index = 0; index < diffResult.length; index++) {
const [kind, str] = diffResult[index];
switch (kind) {
case 1:
{
if (str.length > 0) {
const strBuf = createBase64Buffer(str);
out.push(
createResponseHeader("I", strBuf.length),
strBuf,
newline
);
}
}
break;
case -1:
out.push(
createResponseHeader("D", punycode["ucs2"]["decode"](str).length)
);
break;
case 0:
if (index < diffResult.length - 1) {
out.push(
createResponseHeader(
"M",
punycode["ucs2"]["decode"](str).length
)
);
}
}
}
out.push(createResponseHeader("T", timeAfterFormat));
out.push(createResponseHeader("T", timeBeforeFormat));
if (Number.isFinite(result["cursorOffset"])) {
out.push(createResponseHeader("C", result["cursorOffset"]));
}
out.push(Z);
process.stdout.write(Buffer.concat(out));
} catch (e) {
writeError(e);
}
}
/**
* Handle a request for options.
*
* - Extract the filepath from the packet
*
* - Find the corresponding Prettier version
*
* - Resolve Prettier configuration for the file
*
* - Respond with an object containing the Prettier configuration along with
* miscellaneous info, serialized to JSON, encoded as Base 64.
*
* @param {!Buffer} packet
*/
function handleOptions(packet) {
try {
const newlineIndex1 = packet.indexOf(10);
if (newlineIndex1 < 0) {
protocolError();
}
const editorconfig = packet[1] === "E".charCodeAt(0);
const inferParser = packet[2] === "I".charCodeAt(0);
const filepath = packet.toString("utf-8", 3, newlineIndex1);
const newlineIndex2 = packet.indexOf(10, newlineIndex1 + 1);
if (newlineIndex2 < 0) {
protocolError();
}
const parsersString = packet.toString(
"utf-8",
newlineIndex1 + 1,
newlineIndex2
);
const parsers = parseParsers(parsersString);
const prettier = getPrettierForPath(filepath);
const options =
prettier.resolveConfig.sync(filepath, { editorconfig }) || {};
let optionsStr;
options["parser"] = function (_text, _parsers, options) {
optionsStr = JSON.stringify({
["versions"]: Object.assign({}, process["versions"], {
["prettier"]: prettier.version,
}),
["options"]: options,
["bestParser"]: bestParser(
prettier,
parsers,
options,
inferParser ? filepath : null
),
});
return { type: "NullLiteral" };
};
prettier.format(".", options);
const optionsBuf = createBase64Buffer(optionsStr);
process.stdout.write(
Buffer.concat([
createResponseHeader("O", optionsBuf.length),
optionsBuf,
newline,
Z,
])
);
} catch (e) {
writeError(e);
}
}
/**
* Handle a data packet -- a stream of bytes received on stdin, ended by a
* double linefeed.
*
* @param {!Array<!Buffer>} packetBuffers is an array of Buffers that make up
* the packet when concatenated.
*/
function handlePacket(packetBuffers) {
const packet = Buffer.concat(packetBuffers);
if (packet[0] === "f".charCodeAt(0)) {
handleFormat(packet);
} else if (packet[0] === "o".charCodeAt(0)) {
handleOptions(packet);
} else if (packet[0] === "w".charCodeAt(0)) {
handleWarmup(packet);
} else {
protocolError();
}
}
/*
* Main loop: receive data from stdin; when a double newline is received, pass
* all data received so far to `handlePacket`.
*/
const buffers = [];
process.stdin["on"]("data", (slice) => {
while (slice.length > 0) {
const lastBuffer =
buffers.length > 0 ? buffers[buffers.length - 1] : null;
if (
lastBuffer &&
lastBuffer[lastBuffer.length - 1] == 10 &&
slice[0] == 10
) {
buffers.push(slice.slice(0, 1));
slice = slice.slice(1);
handlePacket(buffers);
buffers.length = 0;
} else {
const index = slice.indexOf("\n\n");
if (index < 0) {
buffers.push(slice);
break;
} else {
buffers.push(slice.slice(0, index + 2));
slice = slice.slice(index + 2);
handlePacket(buffers);
buffers.length = 0;
}
}
}
});
};