-
Notifications
You must be signed in to change notification settings - Fork 97
/
Copy pathindex.ts
105 lines (88 loc) · 3.06 KB
/
index.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
import test from 'ava';
import { readdirSync, readFileSync, existsSync } from 'fs';
import { format } from 'prettier';
import { VERSION } from 'svelte/compiler';
import * as SveltePlugin from '../../src';
const isSvelte5Plus = Number(VERSION.split('.')[0]) >= 5;
let dirs = readdirSync('test/formatting/samples');
const printerFilesHaveOnly = readdirSync('test/printer/samples').some(
(f) => f.endsWith('.only.html') || f.endsWith('.only.md'),
);
const endsWithOnly = (f: string): boolean => f.endsWith('.only');
const hasOnly = printerFilesHaveOnly || dirs.some(endsWithOnly);
dirs = !hasOnly ? dirs : dirs.filter(endsWithOnly);
if (process.env.CI && hasOnly) {
throw new Error('.only tests present');
}
for (const dir of dirs) {
const input = readFileSync(`test/formatting/samples/${dir}/input.html`, 'utf-8').replace(
/\r?\n/g,
'\n',
);
const expectedOutput = readFileSync(
`test/formatting/samples/${dir}/output.html`,
'utf-8',
).replace(/\r?\n/g, '\n');
const options = readOptions(`test/formatting/samples/${dir}/options.json`);
// Tests attribute quoting changes, which are different in Svelte 5
if (dir.endsWith('strict-mode-true') && isSvelte5Plus) continue;
test(`formatting: ${dir}`, async (t) => {
let onTestCompleted;
if (options.expectSyntaxErrors) {
onTestCompleted = doNotLogSyntaxErrors();
}
try {
const actualOutput = await format(input, {
parser: 'svelte',
plugins: [SveltePlugin],
tabWidth: 4,
...options,
});
t.is(
expectedOutput,
actualOutput,
`Expected:\n${expectedOutput}\n\nActual:\n${actualOutput}`,
);
// Reprint to check that another format outputs the same code
const actualOutput2 = await format(actualOutput, {
parser: 'svelte',
plugins: [SveltePlugin],
tabWidth: 4,
...options,
});
t.is(
expectedOutput,
actualOutput2,
`Reprint failed. Expected:\n${expectedOutput}\n\nActual:\n${actualOutput2}`,
);
} finally {
if (onTestCompleted) {
onTestCompleted();
}
}
});
}
/**
* Overwrite `console.error` so as to not report any syntax errors
* (there are tests that intentionally produce them).
* Returns a function that restores the original `console.error`.
*/
function doNotLogSyntaxErrors(): () => {} {
const delegate = console.error;
console.error = (...args: any[]) => {
const e = args[0];
if (e instanceof SyntaxError) {
// swallow
} else {
delegate(...args);
}
};
return () => (console.error = delegate);
}
function readOptions(fileName: string) {
if (!existsSync(fileName)) {
return {};
}
const fileContents = readFileSync(fileName, 'utf-8');
return JSON.parse(fileContents);
}