-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
common.ts
104 lines (99 loc) · 2.65 KB
/
common.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
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import type { Options } from 'prettier';
import { format } from 'prettier';
import type { AttributeToken } from 'pug-lexer';
import { plugin } from 'src/index';
/**
* Creates a fake attribute token.
*
* @param name Name of the attribute.
* @param val Value of the attribute. Default `'dummy'`.
* @returns A fake attribute token.
*/
export function createAttributeToken(
name: string,
val: string | boolean = 'dummy',
): AttributeToken {
return {
name,
val,
mustEscape: false,
type: 'attribute',
loc: {
start: { line: 0, column: 0 },
end: { line: 0, column: 0 },
},
};
}
/**
* Options for `compareFiles`.
*/
export interface CompareFilesOptions {
/**
* Name of the source code file. Default `'unformatted.pug'`.
*/
source?: string;
/**
* Name of the target code file. Default `'formatted.pug'`.
*
* Pass `null` to explicitly only check the given source.
*/
target?: string | null;
/**
* Further format options.
*
* You can also override the `parser` and `plugins` key.
*
* @default { parser: 'pug', plugins: [plugin] }
*/
formatOptions?: Options;
}
/**
* Result of the comparison.
*/
export interface CompareFilesResult {
/**
* The code of the target file.
*
* `null` if target was also `null`.
*/
readonly expected: string | null;
/**
* The code of the source file.
*/
readonly code: string;
/**
* The actual formatted result.
*/
readonly actual: string;
}
/**
* Compare two files with each other and returns the result to be passed in expect calls.
*
* @param dirname Pass `__dirname`, so the function can relative resolve the files.
* @param param1 Compare options.
* @param param1.source The source file. Default `'unformatted.pug'`.
* @param param1.target The target file. Default `'formatted.pug'`. Pass `null` to explicitly only check the given source.
* @param param1.formatOptions Further format options. Default `{ parser: 'pug', plugins: [plugin] }`. You can also override the parser and plugins key.
* @returns The result to be passed in expect calls.
*/
export function compareFiles(
dirname: string,
{
source = 'unformatted.pug',
target = 'formatted.pug',
formatOptions = {},
}: CompareFilesOptions = {},
): CompareFilesResult {
const expected: string | null = target
? readFileSync(resolve(dirname, target), 'utf8')
: null;
const code: string = readFileSync(resolve(dirname, source), 'utf8');
const actual: string = format(code, {
parser: 'pug',
plugins: [plugin],
...formatOptions,
});
return { expected, code, actual };
}