1 | /**
|
2 | * @fileoverview Rule to enforce a single linebreak style.
|
3 | * @author Erik Mueller
|
4 | */
|
5 |
|
6 | ;
|
7 |
|
8 | //------------------------------------------------------------------------------
|
9 | // Rule Definition
|
10 | //------------------------------------------------------------------------------
|
11 |
|
12 | module.exports = {
|
13 | meta: {
|
14 | docs: {
|
15 | description: "enforce consistent linebreak style",
|
16 | category: "Stylistic Issues",
|
17 | recommended: false
|
18 | },
|
19 |
|
20 | fixable: "whitespace",
|
21 |
|
22 | schema: [
|
23 | {
|
24 | enum: ["unix", "windows"]
|
25 | }
|
26 | ]
|
27 | },
|
28 |
|
29 | create(context) {
|
30 |
|
31 | const EXPECTED_LF_MSG = "Expected linebreaks to be 'LF' but found 'CRLF'.",
|
32 | EXPECTED_CRLF_MSG = "Expected linebreaks to be 'CRLF' but found 'LF'.";
|
33 |
|
34 | const sourceCode = context.getSourceCode();
|
35 |
|
36 | //--------------------------------------------------------------------------
|
37 | // Helpers
|
38 | //--------------------------------------------------------------------------
|
39 |
|
40 | /**
|
41 | * Builds a fix function that replaces text at the specified range in the source text.
|
42 | * @param {int[]} range The range to replace
|
43 | * @param {string} text The text to insert.
|
44 | * @returns {Function} Fixer function
|
45 | * @private
|
46 | */
|
47 | function createFix(range, text) {
|
48 | return function(fixer) {
|
49 | return fixer.replaceTextRange(range, text);
|
50 | };
|
51 | }
|
52 |
|
53 | //--------------------------------------------------------------------------
|
54 | // Public
|
55 | //--------------------------------------------------------------------------
|
56 |
|
57 | return {
|
58 | Program: function checkForlinebreakStyle(node) {
|
59 | const linebreakStyle = context.options[0] || "unix",
|
60 | expectedLF = linebreakStyle === "unix",
|
61 | expectedLFChars = expectedLF ? "\n" : "\r\n",
|
62 | source = sourceCode.getText(),
|
63 | pattern = /\r\n|\r|\n|\u2028|\u2029/g;
|
64 | let match;
|
65 |
|
66 | let i = 0;
|
67 |
|
68 | while ((match = pattern.exec(source)) !== null) {
|
69 | i++;
|
70 | if (match[0] === expectedLFChars) {
|
71 | continue;
|
72 | }
|
73 |
|
74 | const index = match.index;
|
75 | const range = [index, index + match[0].length];
|
76 |
|
77 | context.report({
|
78 | node,
|
79 | loc: {
|
80 | line: i,
|
81 | column: sourceCode.lines[i - 1].length
|
82 | },
|
83 | message: expectedLF ? EXPECTED_LF_MSG : EXPECTED_CRLF_MSG,
|
84 | fix: createFix(range, expectedLFChars)
|
85 | });
|
86 | }
|
87 | }
|
88 | };
|
89 | }
|
90 | };
|