This repository was archived by the owner on Mar 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 509
/
Copy pathdisallow-empty-blocks.js
104 lines (90 loc) · 2.72 KB
/
disallow-empty-blocks.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/**
* Disallows empty blocks (except for catch blocks).
*
* Type: `Boolean` or `Object`
*
* Values:
* - `true` for default behavior (strict mode, no empty blocks allowed)
* - `Object`:
* - `'allExcept'` array of exceptions:
* - `'comments'` blocks containing only comments are not considered empty
*
* JSHint: [`noempty`](http://jshint.com/docs/options/#noempty)
*
* #### Example
*
* ```js
* "disallowEmptyBlocks": true
* ```
*
* ##### Valid
*
* ```js
* if ( a == b ) { c = d; }
* try { a = b; } catch( e ){}
* ```
*
* ##### Invalid
*
* ```js
* if ( a == b ) { } else { c = d; }
* ```
*/
var assert = require('assert');
module.exports = function() {};
module.exports.prototype = {
configure: function(options) {
var optionName = this.getOptionName();
if (typeof options !== 'object') {
assert(
options === true,
optionName + ' option requires a true value or an object like: { allExcept: [\'comments\'] }'
);
var _options = {
allExcept: []
};
return this.configure(_options);
}
assert(
Array.isArray(options.allExcept),
'Property `allExcept` in ' + optionName + ' should be an array of strings'
);
this._exceptComments = options.allExcept.indexOf('comments') > -1;
},
getOptionName: function() {
return 'disallowEmptyBlocks';
},
check: function(file, errors) {
var exceptComments = this._exceptComments;
function canSkip(token) {
if (!exceptComments) {
return false;
}
var canSkipToken = false;
var tokenLoc = token.getLoc();
file.getComments().forEach(function(comment) {
var commentLoc = comment.getLoc();
if (commentLoc.start.line >= tokenLoc.start.line &&
commentLoc.end.line <= tokenLoc.end.line) {
canSkipToken = true;
}
});
return canSkipToken;
}
file.iterateNodesByType('BlockStatement', function(node) {
if (node.body.length) {
return true;
}
if (canSkip(node)) {
return true;
}
if (node.parentElement.type !== 'CatchClause' &&
node.parentElement.type !== 'FunctionDeclaration' &&
node.parentElement.type !== 'FunctionExpression' &&
node.parentElement.type !== 'ArrowFunctionExpression' &&
node.parentElement.type !== 'ObjectMethod') {
errors.add('Empty block found', node.lastChild);
}
});
}
};