forked from sveltejs/eslint-plugin-svelte
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.ts
256 lines (228 loc) · 6.83 KB
/
utils.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
import fs from "fs"
import path from "path"
import type { RuleTester } from "eslint"
import { Linter } from "eslint"
import * as svelteESLintParser from "svelte-eslint-parser"
// eslint-disable-next-line @typescript-eslint/no-require-imports -- tests
import plugin = require("../../src/index")
import { applyFixes } from "./source-code-fixer"
/**
* Prevents leading spaces in a multiline template literal from appearing in the resulting string
*/
export function unIndent(strings: readonly string[]): string {
const templateValue = strings[0]
const lines = templateValue.split("\n")
const minLineIndent = getMinIndent(lines)
return lines.map((line) => line.slice(minLineIndent)).join("\n")
}
/**
* for `code` and `output`
*/
export function unIndentCodeAndOutput([code]: readonly string[]): (
args: readonly string[],
) => {
code: string
output: string
} {
const codeLines = code.split("\n")
const codeMinLineIndent = getMinIndent(codeLines)
return ([output]: readonly string[]) => {
const outputLines = output.split("\n")
const minLineIndent = Math.min(getMinIndent(outputLines), codeMinLineIndent)
return {
code: codeLines.map((line) => line.slice(minLineIndent)).join("\n"),
output: outputLines.map((line) => line.slice(minLineIndent)).join("\n"),
}
}
}
/**
* Get number of minimum indent
*/
function getMinIndent(lines: string[]) {
const lineIndents = lines
.filter((line) => line.trim())
.map((line) => / */u.exec(line)![0].length)
return Math.min(...lineIndents)
}
/**
* Load test cases
*/
export function loadTestCases(
ruleName: string,
options?: {
additionals?: {
valid?: (RuleTester.ValidTestCase | string)[]
invalid?: RuleTester.InvalidTestCase[]
}
filter?: (file: string) => boolean
},
): {
valid: RuleTester.ValidTestCase[]
invalid: RuleTester.InvalidTestCase[]
} {
const validFixtureRoot = path.resolve(
__dirname,
`../fixtures/rules/${ruleName}/valid/`,
)
const invalidFixtureRoot = path.resolve(
__dirname,
`../fixtures/rules/${ruleName}/invalid/`,
)
const filter = options?.filter ?? (() => true)
const valid = listupInput(validFixtureRoot)
.filter(filter)
.map((inputFile) => getConfig(ruleName, inputFile))
const fixable = plugin.rules[ruleName].meta.fixable != null
const invalid = listupInput(invalidFixtureRoot)
.filter(filter)
.map((inputFile) => {
const config = getConfig(ruleName, inputFile)
const errorFile = inputFile.replace(/input\.[a-z]+$/u, "errors.json")
const outputFile = inputFile.replace(/input\.[a-z]+$/u, "output.svelte")
let errors
try {
errors = fs.readFileSync(errorFile, "utf8")
} catch (e) {
writeFixtures(ruleName, inputFile)
errors = fs.readFileSync(errorFile, "utf8")
}
config.errors = JSON.parse(errors)
if (fixable) {
let output
try {
output = fs.readFileSync(outputFile, "utf8")
} catch (e) {
writeFixtures(ruleName, inputFile)
output = fs.readFileSync(outputFile, "utf8")
}
config.output = output
}
return config
})
if (options?.additionals) {
if (options.additionals.valid) {
valid.push(...options.additionals.valid)
}
if (options.additionals.invalid) {
invalid.push(...options.additionals.invalid)
}
}
for (const test of valid) {
if (!test.code) {
throw new Error(`Empty code: ${test.filename}`)
}
}
for (const test of invalid) {
if (!test.code) {
throw new Error(`Empty code: ${test.filename}`)
}
}
return {
valid,
invalid,
}
}
function listupInput(rootDir: string) {
return [...itrListupInput(rootDir)]
}
function* itrListupInput(rootDir: string): IterableIterator<string> {
for (const filename of fs.readdirSync(rootDir)) {
if (filename.startsWith("_")) {
// ignore
continue
}
const abs = path.join(rootDir, filename)
if (path.basename(filename, path.extname(filename)).endsWith("input")) {
yield abs
} else if (fs.statSync(abs).isDirectory()) {
yield* itrListupInput(abs)
}
}
}
// Necessary because of this:
// https://github.com/eslint/eslint/issues/14936#issuecomment-906746754
function applySuggestion(code: string, suggestion: Linter.LintSuggestion) {
const { fix } = suggestion
return `${code.slice(0, fix.range[0])}${fix.text}${code.slice(fix.range[1])}`
}
function writeFixtures(
ruleName: string,
inputFile: string,
{ force }: { force?: boolean } = {},
) {
const linter = getLinter(ruleName)
const errorFile = inputFile.replace(/input\.[a-z]+$/u, "errors.json")
const outputFile = inputFile.replace(/input\.[a-z]+$/u, "output.svelte")
const config = getConfig(ruleName, inputFile)
const result = linter.verify(
config.code,
{
rules: {
[ruleName]: ["error", ...(config.options || [])],
},
parser: "svelte-eslint-parser",
parserOptions: {
ecmaVersion: 2020,
sourceType: "module",
parser: {
ts: "@typescript-eslint/parser",
js: "espree",
},
},
},
config.filename,
)
if (force || !fs.existsSync(errorFile)) {
fs.writeFileSync(
errorFile,
`${JSON.stringify(
result.map((m) => ({
message: m.message,
line: m.line,
column: m.column,
suggestions: m.suggestions
? m.suggestions.map((s) => ({
desc: s.desc,
messageId: s.messageId,
// Need to have this be the *fixed* output, not just the fix content or anything
output: applySuggestion(config.code, s),
}))
: null,
})),
null,
2,
)}\n`,
"utf8",
)
}
if (force || !fs.existsSync(outputFile)) {
const output = applyFixes(config.code, result).output
if (plugin.rules[ruleName].meta.fixable != null) {
fs.writeFileSync(outputFile, output, "utf8")
}
}
}
function getLinter(ruleName: string) {
const linter = new Linter()
// @ts-expect-error for test
linter.defineParser("svelte-eslint-parser", svelteESLintParser)
linter.defineRule(ruleName, plugin.rules[ruleName] as any)
return linter
}
function getConfig(ruleName: string, inputFile: string) {
const filename = inputFile.slice(inputFile.indexOf(ruleName))
const code = fs.readFileSync(inputFile, "utf8")
let config
let configFile: string = inputFile.replace(/input\.[a-z]+$/u, "config.json")
if (!fs.existsSync(configFile)) {
configFile = path.join(path.dirname(inputFile), "_config.json")
}
if (fs.existsSync(configFile)) {
config = JSON.parse(fs.readFileSync(configFile, "utf8"))
}
const parser =
path.extname(filename) === ".svelte"
? require.resolve("svelte-eslint-parser")
: undefined
return Object.assign({ parser }, config, { code, filename })
}