-
-
Notifications
You must be signed in to change notification settings - Fork 26
/
util.ts
496 lines (442 loc) · 11.8 KB
/
util.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
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
import fs from "node:fs";
import os from "node:os";
// @ts-ignore
// eslint-disable-next-line
import phpPlugin from "@prettier/plugin-php/standalone";
import chalk from "chalk";
import detectIndent from "detect-indent";
/* eslint-disable max-len */
import _ from "lodash";
import * as prettier from "prettier/standalone";
import replaceAsync from "string-replace-async";
import {
indentStartTokens,
phpKeywordEndTokens,
phpKeywordStartTokens,
} from "./indent";
import { nestedParenthesisRegex } from "./regex";
import type { EndOfLine } from "./runtimeConfig";
export const optional = (obj: any) => {
const chain = {
get() {
return null;
},
};
if (_.isUndefined(obj) || _.isNull(obj)) {
return chain;
}
return obj;
};
export async function readFile(path: any) {
return new Promise((resolve, reject) => {
fs.readFile(path, (error: any, data: any) =>
error ? reject(error) : resolve(data),
);
});
}
export function splitByLines(content: any) {
if (!content) {
return "";
}
return content.split(/\r\n|\n|\r/);
}
export type FormatPhpOption = {
noPhpSyntaxCheck?: boolean;
printWidth?: number;
trailingCommaPHP?: boolean;
phpVersion?: string;
noSingleQuote?: boolean;
};
export const printWidthForInline = 1000;
const defaultFormatPhpOption = {
noPhpSyntaxCheck: false,
printWidth: printWidthForInline,
trailingCommaPHP: true,
phpVersion: "8.1",
noSingleQuote: false,
};
export async function formatStringAsPhp(
content: any,
params: FormatPhpOption = {},
): Promise<string> {
const options = {
...defaultFormatPhpOption,
...params,
};
const adjust = params.adjustPrintWidthBy ?? 0;
const printWidth = params.useProjectPrintWidth
? options.printWidth - adjust
: printWidthForInline;
try {
return await prettier.format(content.replace(/\n$/, ""), {
parser: "php",
printWidth,
singleQuote: !options.noSingleQuote,
// @ts-ignore
phpVersion: options.phpVersion,
trailingCommaPHP: options.trailingCommaPHP,
plugins: [phpPlugin],
});
} catch (error) {
if (options.noPhpSyntaxCheck === false) {
throw error;
}
return content;
}
}
export async function formatRawStringAsPhp(
content: string,
params: FormatPhpOption = {},
) {
const options = {
...defaultFormatPhpOption,
...params,
};
try {
return (
await prettier.format(`<?php echo ${content} ?>`, {
parser: "php",
printWidth: options.printWidth,
singleQuote: !options.noSingleQuote,
// @ts-ignore
phpVersion: options.phpVersion,
trailingCommaPHP: options.trailingCommaPHP,
plugins: [phpPlugin],
})
).replace(/<\?php echo (.*)?\?>/gs, (match: any, p1: any) =>
p1.trim().replace(/;\s*$/, ""),
);
} catch (error) {
if (options.noPhpSyntaxCheck === false) {
throw error;
}
return content;
}
}
export async function getArgumentsCount(expression: string) {
const code = `<?php tmp_func${expression}; ?>`;
try {
// @ts-ignore
// eslint-disable-next-line no-underscore-dangle
const { ast } = await prettier.__debug.parse(code, {
parser: "php",
phpVersion: "8.1",
plugins: [phpPlugin],
});
return ast.children[0].expression.arguments.length || 0;
} catch (e) {
return 0;
}
}
export function normalizeIndentLevel(length: any) {
if (length < 0) {
return 0;
}
return length;
}
export function printDiffs(diffs: any) {
return Promise.all(
_.map(diffs, async (diff: any) => {
process.stdout.write(`path: ${chalk.bold(diff.path)}:${diff.line}\n`);
process.stdout.write(chalk.red(`--${diff.original}\n`));
process.stdout.write(chalk.green(`++${diff.formatted}\n`));
}),
);
}
export function generateDiff(
path: any,
originalLines: any,
formattedLines: any,
) {
const diff = _.map(originalLines, (originalLine: any, index: any) => {
if (_.isEmpty(originalLine)) {
return null;
}
if (originalLine === formattedLines[index]) {
return null;
}
return {
path,
line: index + 1,
original: originalLine,
formatted: formattedLines[index],
};
});
return _.without(diff, null);
}
export async function prettifyPhpContentWithUnescapedTags(
content: string,
options: FormatPhpOption,
) {
const directives = _.without(
indentStartTokens,
"@switch",
"@forelse",
"@php",
).join("|");
const directiveRegexes = new RegExp(
// eslint-disable-next-line max-len
`(?!\\/\\*.*?\\*\\/)(${directives})(\\s*?)${nestedParenthesisRegex}`,
"gmi",
);
return new Promise((resolve) => resolve(content))
.then((res: any) =>
replaceAsync(
res,
directiveRegexes,
async (match: any, p1: any, p2: any, p3: any) =>
(
await formatStringAsPhp(
`<?php ${p1.substr("1")}${p2}(${p3}) ?>`,
options,
)
)
.replace(
/<\?php\s(.*?)(\s*?)\((.*?)\);*\s\?>\n/gs,
(match2: any, j1: any, j2: any, j3: any) =>
`@${j1.trim()}${j2}(${j3.trim()})`,
)
.replace(/([\n\s]*)->([\n\s]*)/gs, "->")
.replace(/,\)$/, ")")
.replace(
/(?:\n\s*)* as(?= (?:&{0,1}\$[\w]+|list|\[\$[\w]+))/g,
" as",
),
),
)
.then((res) => formatStringAsPhp(res, options));
}
export async function prettifyPhpContentWithEscapedTags(
content: string,
options: FormatPhpOption,
) {
return new Promise((resolve) => resolve(content))
.then((res: any) => _.replace(res, /{!!/g, "<?php /*escaped*/"))
.then((res) => _.replace(res, /!!}/g, "/*escaped*/ ?>\n"))
.then((res) => formatStringAsPhp(res, options))
.then((res) => _.replace(res, /<\?php\s\/\*escaped\*\//g, "{!! "))
.then((res) => _.replace(res, /\/\*escaped\*\/\s\?>\n/g, " !!}"));
}
export async function removeSemicolon(content: any) {
return new Promise((resolve) => {
resolve(content);
})
.then((res: any) => _.replace(res, /;[\n\s]*!!\}/g, " !!}"))
.then((res) => _.replace(res, /;[\s\n]*!!}/g, " !!}"))
.then((res) => _.replace(res, /;[\n\s]*}}/g, " }}"))
.then((res) => _.replace(res, /; }}/g, " }}"))
.then((res) => _.replace(res, /; --}}/g, " --}}"));
}
export async function formatAsPhp(content: string, options: FormatPhpOption) {
return prettifyPhpContentWithUnescapedTags(content, options);
}
export async function preserveOriginalPhpTagInHtml(content: any) {
return new Promise((resolve) => resolve(content))
.then((res: any) => _.replace(res, /<\?php/g, "/** phptag_start **/"))
.then((res) => _.replace(res, /\?>/g, "/** end_phptag **/"));
}
export function revertOriginalPhpTagInHtml(content: any) {
return new Promise((resolve) => resolve(content))
.then((res: any) =>
_.replace(res, /\/\*\*[\s\n]*?phptag_start[\s\n]*?\*\*\//gs, "<?php"),
)
.then((res) =>
_.replace(res, /\/\*\*[\s\n]*?end_phptag[\s\n]*?\*\*\/[\s];\n/g, "?>;"),
)
.then((res) =>
_.replace(res, /\/\*\*[\s\n]*?end_phptag[\s\n]*?\*\*\//g, "?>"),
);
}
export function indent(content: any, level: any, options: any) {
const lines = content.split("\n");
return _.map(lines, (line: any, index: any) => {
if (!line.match(/\w/)) {
return line;
}
const ignoreFirstLine = optional(options).ignoreFirstLine || false;
if (ignoreFirstLine && index === 0) {
return line;
}
const originalLineWhitespaces = detectIndent(line).amount;
const indentChar = optional(options).useTabs ? "\t" : " ";
const indentSize = optional(options).indentSize || 4;
const whitespaces = originalLineWhitespaces + indentSize * level;
if (whitespaces < 0) {
return line;
}
return indentChar.repeat(whitespaces) + line.trimLeft();
}).join("\n");
}
export function unindent(
directive: any,
content: any,
level: any,
options: any,
) {
const lines = content.split("\n");
return _.map(lines, (line: any) => {
if (!line.match(/\w/)) {
return line;
}
const originalLineWhitespaces = detectIndent(line).amount;
const indentChar = optional(options).useTabs ? "\t" : " ";
const indentSize = optional(options).indentSize || 4;
const whitespaces = originalLineWhitespaces - indentSize * level;
if (whitespaces < 0) {
return line;
}
return indentChar.repeat(whitespaces) + line.trimLeft();
}).join("\n");
}
export function preserveDirectives(content: any) {
const startTokens = _.without(phpKeywordStartTokens, "@case");
const endTokens = _.without(phpKeywordEndTokens, "@break");
return new Promise((resolve) => resolve(content))
.then((res: any) => {
const regex = new RegExp(
`(${startTokens.join("|")})([\\s]*?)${nestedParenthesisRegex}`,
"gis",
);
return _.replace(
res,
regex,
(match: any, p1: any, p2: any, p3: any) =>
`<beautifyTag start="${p1}${p2}" exp="^^^${_.escape(p3)}^^^">`,
);
})
.then((res: any) => {
const regex = new RegExp(
`(?!end=".*)(${endTokens.join("|")})(?!.*")`,
"gi",
);
return _.replace(
res,
regex,
(match: any, p1: any) => `</beautifyTag end="${p1}">`,
);
});
}
export function preserveDirectivesInTag(content: any) {
return new Promise((resolve) => {
const regex = new RegExp(
`(<[^>]*?)(${phpKeywordStartTokens.join(
"|",
)})([\\s]*?)${nestedParenthesisRegex}(.*?)(${phpKeywordEndTokens.join(
"|",
)})([^>]*?>)`,
"gis",
);
resolve(
_.replace(
content,
regex,
(
match: any,
p1: any,
p2: any,
p3: any,
p4: any,
p5: any,
p6: any,
p7: any,
) =>
`${p1}|-- start="${p2}${p3}" exp="^^^${p4}^^^" body="^^^${_.escape(
_.trim(p5),
)}^^^" end="${p6}" --|${p7}`,
),
);
});
}
export function revertDirectives(content: any) {
return new Promise((resolve) => resolve(content))
.then((res: any) =>
_.replace(
res,
/<beautifyTag.*?start="(.*?)".*?exp=".*?\^\^\^(.*?)\^\^\^.*?"\s*>/gs,
(match: any, p1: any, p2: any) => `${p1}(${_.unescape(p2)})`,
),
)
.then((res) =>
_.replace(
res,
/<\/beautifyTag.*?end="(.*?)"\s*>/gs,
(match: any, p1: any) => `${p1}`,
),
);
}
export function revertDirectivesInTag(content: any) {
return new Promise((resolve) => resolve(content))
.then((res: any) =>
_.replace(
res,
/\|--.*?start="(.*?)".*?exp=".*?\^\^\^(.*?)\^\^\^.*?"(.*?)body=".*?\^\^\^(.*?)\^\^\^.*?".*?end="(.*?)".*?--\|/gs,
(match: any, p1: any, p2: any, p3: any, p4: any, p5: any) =>
`${_.trimStart(p1)}(${p2}) ${_.unescape(p4)} ${p5}`,
),
)
.then((res) =>
_.replace(
res,
/\/-- end="(.*?)"--\//gs,
(match: any, p1: any) => `${p1}`,
),
);
}
export function printDescription() {
const returnLine = "\n\n";
process.stdout.write(returnLine);
process.stdout.write(chalk.bold.green("Fixed: F\n"));
process.stdout.write(chalk.bold.red("Errors: E\n"));
process.stdout.write(chalk.bold("Not Changed: ") + chalk.bold.green(".\n"));
}
const escapeTags = [
"/\\*\\* phptag_start \\*\\*/",
"/\\*\\* end_phptag \\*\\*/",
"/\\*escaped\\*/",
"__BLADE__;",
"/\\* blade_comment_start \\*/",
"/\\* blade_comment_end \\*/",
"/\\*\\*\\*script_placeholder\\*\\*\\*/",
"blade___non_native_scripts_",
"blade___scripts_",
"blade___html_tags_",
"beautifyTag",
"@customdirective",
"@elsecustomdirective",
"@endcustomdirective",
"x-slot --___\\d+___--",
"___attrs_+\\d+___",
];
export function checkResult(formatted: any) {
if (new RegExp(escapeTags.join("|")).test(formatted)) {
throw new Error(
[
"Can't format blade: something goes wrong.",
// eslint-disable-next-line max-len
"Please check if template is too complicated or not. Or simplify template might solves issue.",
].join("\n"),
);
}
return formatted;
}
export function escapeReplacementString(string: string) {
return string.replace(/\$/g, "$$$$");
}
export function debugLog(...content: any) {
_.each(content, (item) => {
console.log("------------------- content start -------------------");
console.log(item);
console.log("------------------- content end -------------------");
});
return content;
}
export function getEndOfLine(endOfLine?: EndOfLine): string {
switch (endOfLine) {
case "LF":
return "\n";
case "CRLF":
return "\r\n";
default:
return os.EOL;
}
}