UNPKG

2.35 kBJavaScriptView Raw
1/**
2 * Option to check line break characters
3 *
4 * Types: `String`, `Object`
5 *
6 * Values:
7 * - `String`: setting this is the same as validating the rule using `{character: String, reportOncePerFile: false}`
8 * - `Object`:
9 * - `character`
10 * - `String` specifies the line break character that is allowed. (Values allowed: `"CR"`, `"LF"` or `"CRLF"`)
11 * - `reportOncePerFile`
12 * - `true` specifies that validation for the file should stop running upon encountering the first rule
13 * violation and return the details of that violation in the report
14 * - `false` specifies that all lines in the file should be validated with all rule violations captured in
15 * the final report
16 *
17 * #### Example
18 *
19 * ```js
20 * "validateLineBreaks": "LF"
21 * ```
22 *
23 * ##### Valid for mode `"LF"`
24 * ```js
25 * var x = 1;<LF>
26 * x++;
27 * ```
28 *
29 * ##### Invalid for mode `"LF"`
30 * ```js
31 * var x = 1;<CRLF>
32 * x++;
33 * ```
34 */
35
36var assert = require('assert');
37
38var LINE_BREAKS = /\r\n|\n|\r/g;
39
40module.exports = function() {};
41
42module.exports.prototype = {
43
44 configure: function(options) {
45 assert(
46 typeof options === 'string' || typeof options === 'object',
47 this.getOptionName() + ' option requires string or object value'
48 );
49
50 if (typeof options === 'string') {
51 options = { character: options };
52 }
53
54 var lineBreaks = {
55 CR: '\r',
56 LF: '\n',
57 CRLF: '\r\n'
58 };
59 this._allowedLineBreak = lineBreaks[options.character];
60
61 this._reportOncePerFile = options.reportOncePerFile !== false;
62 },
63
64 getOptionName: function() {
65 return 'validateLineBreaks';
66 },
67
68 check: function(file, errors) {
69 var lines = file.getLines();
70 if (lines.length < 2) {
71 return;
72 }
73
74 file.getProgram().selectTokensByType('Whitespace').some(function(whitespace) {
75 LINE_BREAKS.lastIndex = 0;
76 var match;
77 while ((match = LINE_BREAKS.exec(whitespace.value)) !== null) {
78 if (match[0] !== this._allowedLineBreak) {
79 errors.add('Invalid line break', whitespace, match.index);
80 return this._reportOncePerFile;
81 }
82 }
83 }, this);
84 }
85
86};