UNPKG

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