TypeScript/scripts/eslint/rules/simple-indent.ts

70 lines
2.3 KiB
TypeScript
Raw Normal View History

2019-08-04 13:27:55 +02:00
import { TSESTree } from "@typescript-eslint/experimental-utils";
2019-08-02 17:27:06 +02:00
import { createRule } from "./utils";
export = createRule({
2019-08-02 17:27:06 +02:00
name: "simple-indent",
meta: {
docs: {
description: "Enforce consistent indentation",
category: "Stylistic Issues",
recommended: "error",
},
messages: {
simpleIndentError: "4 space indentation expected",
},
2019-08-04 13:27:55 +02:00
fixable: "whitespace",
2019-08-02 17:27:06 +02:00
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;
2019-08-04 13:27:55 +02:00
let totalLen = 0;
2019-08-02 17:27:06 +02:00
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({
2019-08-04 13:27:55 +02:00
messageId: "simpleIndentError",
2019-08-02 17:27:06 +02:00
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;
}
2019-08-04 13:27:55 +02:00
};
2019-08-02 17:27:06 +02:00
return {
Program: checkIndent,
2019-08-04 13:27:55 +02:00
};
2019-08-02 17:27:06 +02:00
},
});