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