1 | import * as prettier from 'prettier';
|
2 | import { log } from '../utils/log';
|
3 |
|
4 | const formatOptions: prettier.Options = {
|
5 | semi: true,
|
6 | singleQuote: true,
|
7 | trailingComma: 'es5',
|
8 | tabWidth: 4,
|
9 | printWidth: 85,
|
10 | endOfLine: 'lf',
|
11 | arrowParens: 'always',
|
12 | parser: 'typescript',
|
13 | };
|
14 |
|
15 | export function formatFunctionSignature(text: string): string {
|
16 | const varLike = `let ${text}`;
|
17 | return formatVariableSignature(varLike).replace(/^let\s/, '');
|
18 | }
|
19 |
|
20 | export function formatVariableSignature(text: string): string {
|
21 |
|
22 | const escapedText = text.replace('default:', '_______:');
|
23 | return formatText(escapedText).replace('_______:', 'default:');
|
24 | }
|
25 |
|
26 | export function formatClassMember(text: string): string {
|
27 | const wrapped = `class C { ${text} }`;
|
28 | return formatWrappedMember(wrapped);
|
29 | }
|
30 |
|
31 | export function formatInterfaceMember(text: string): string {
|
32 | const wrapped = `interface I { ${text} }`;
|
33 | return formatWrappedMember(wrapped);
|
34 | }
|
35 |
|
36 | export function formatEnumMember(text: string): string {
|
37 | const wrapped = `enum E { ${text} }`;
|
38 | return formatWrappedMember(wrapped).replace(/,$/, '');
|
39 | }
|
40 |
|
41 | function formatWrappedMember(text: string): string {
|
42 | const formatted = formatText(text);
|
43 | const lines = formatted.split('\n');
|
44 |
|
45 |
|
46 | const member = lines
|
47 | .slice(1, lines.length - 1)
|
48 | .map((line) => line.replace(/^\s{4}/, ''))
|
49 | .join('\n');
|
50 |
|
51 | return member;
|
52 | }
|
53 |
|
54 | export function formatText(text: string): string {
|
55 | let formatted = text
|
56 | .trim()
|
57 | .replace(/^export\s+/, '')
|
58 | .replace(/^default\s+/, '')
|
59 | .replace(/^declare\s+/, '');
|
60 |
|
61 | try {
|
62 | formatted = prettier.format(formatted, formatOptions);
|
63 | } catch (err) {
|
64 |
|
65 | log('formatText: formatting error: %O', { err });
|
66 | }
|
67 |
|
68 | return formatted.trim();
|
69 | }
|