-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathno-trailing-spaces.ts
104 lines (98 loc) · 2.85 KB
/
no-trailing-spaces.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 type { AST } from "svelte-eslint-parser"
import { createRule } from "../utils"
export default createRule("no-trailing-spaces", {
meta: {
type: "layout",
docs: {
description: "disallow trailing whitespace at the end of lines",
category: "Extension Rules",
recommended: false,
extensionRule: "no-trailing-spaces",
conflictWithPrettier: true,
},
fixable: "whitespace",
schema: [
{
type: "object",
properties: {
skipBlankLines: { type: "boolean" },
ignoreComments: { type: "boolean" },
},
additionalProperties: false,
},
],
messages: {
trailingSpace: "Trailing spaces not allowed.",
},
},
create(context) {
const options:
| { skipBlankLines?: boolean; ignoreComments?: boolean }
| undefined = context.options[0]
const skipBlankLines = options?.skipBlankLines || false
const ignoreComments = options?.ignoreComments || false
const sourceCode = context.getSourceCode()
const ignoreLineNumbers = new Set<number>()
if (ignoreComments) {
for (const { type, loc } of sourceCode.getAllComments()) {
const endLine = type === "Block" ? loc.end.line - 1 : loc.end.line
for (let i = loc.start.line; i <= endLine; i++) {
ignoreLineNumbers.add(i)
}
}
}
/**
* Reports a given location.
*/
function report(loc: AST.SourceLocation) {
context.report({
loc,
messageId: "trailingSpace",
fix(fixer) {
return fixer.removeRange([
sourceCode.getIndexFromLoc(loc.start),
sourceCode.getIndexFromLoc(loc.end),
])
},
})
}
/**
* Collects the location of the given node as the ignore line numbers.
*/
function collectIgnoreLineNumbers({ loc }: { loc: AST.SourceLocation }) {
const endLine = loc.end.line - 1
for (let i = loc.start.line; i <= endLine; i++) {
ignoreLineNumbers.add(i)
}
}
return {
TemplateElement: collectIgnoreLineNumbers,
...(ignoreComments
? {
SvelteHTMLComment: collectIgnoreLineNumbers,
}
: {}),
"Program:exit"() {
const lines = sourceCode.lines
for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
const line = lines[lineIndex]
if (skipBlankLines && !line.trim()) {
continue
}
const lineNumber = lineIndex + 1
if (ignoreLineNumbers.has(lineNumber)) {
continue
}
const trimmed = line.trimEnd()
if (trimmed === line) {
continue
}
report({
start: { line: lineNumber, column: trimmed.length },
end: { line: lineNumber, column: line.length },
})
}
},
}
},
})