forked from microsoft/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple-indent.ts
More file actions
69 lines (60 loc) · 2.33 KB
/
simple-indent.ts
File metadata and controls
69 lines (60 loc) · 2.33 KB
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
import { TSESTree } from "@typescript-eslint/experimental-utils";
import { createRule } from "./utils";
export = createRule({
name: "simple-indent",
meta: {
docs: {
description: "Enforce consistent indentation",
category: "Stylistic Issues",
recommended: "error",
},
messages: {
simpleIndentError: "4 space indentation expected",
},
fixable: "whitespace",
schema: [],
type: "layout",
},
defaultOptions: [],
create(context) {
const TAB_SIZE = 4;
const TAB_REGEX = /\t/g;
const sourceCode = context.getSourceCode();
const linebreaks = sourceCode.getText().match(/\r\n|[\r\n\u2028\u2029]/gu);
const checkIndent = (node: TSESTree.Program) => {
const lines = sourceCode.getLines();
const linesLen = lines.length;
let totalLen = 0;
for (let i = 0; i < linesLen; i++) {
const lineNumber = i + 1;
const line = lines[i];
const linebreaksLen = linebreaks && linebreaks[i] ? linebreaks[i].length : 1;
const lineLen = line.length + linebreaksLen;
const matches = /\S/.exec(line);
if (matches && matches.index) {
const indentEnd = matches.index;
const whitespace = line.slice(0, indentEnd);
if (!TAB_REGEX.test(whitespace)) {
totalLen += lineLen;
continue;
}
context.report({
messageId: "simpleIndentError",
node,
loc: { column: indentEnd, line: lineNumber },
fix(fixer) {
const rangeStart = totalLen;
const rangeEnd = rangeStart + indentEnd;
return fixer
.replaceTextRange([rangeStart, rangeEnd], whitespace.replace(TAB_REGEX, " ".repeat(TAB_SIZE)));
}
});
}
totalLen += lineLen;
}
};
return {
Program: checkIndent,
};
},
});