UNPKG

1.55 kBJavaScriptView Raw
1var espree = require('espree');
2var quote = require('quote');
3
4function isJshint(text) {
5 'use strict';
6 return /^jshint\ /.test(text);
7}
8console.assert(isJshint('jshint -W098'));
9console.assert(!isJshint('not jshint'));
10
11function isSingleWord(text) {
12 'use strict';
13 return /^[\w-]*$/.test(text);
14}
15console.assert(isSingleWord('fooBar'));
16console.assert(isSingleWord(''));
17console.assert(isSingleWord('click'));
18console.assert(isSingleWord('browser-specific'));
19console.assert(!isSingleWord('var bar'));
20
21function isValidCode(text) {
22 'use strict';
23 if (isSingleWord(text) || isJshint(text)) {
24 return false;
25 }
26
27 try {
28 var ast = espree.parse(text);
29 return !!ast;
30 } catch (err) {
31 return false;
32 }
33}
34
35function firstLine(str) {
36 'use strict';
37 return str.split('\n')[0];
38}
39
40function cut(str) {
41 'use strict';
42 var line = firstLine(str);
43 var MAX_LENGTH = 20;
44 if (line.length > MAX_LENGTH) {
45 line = line.substr(0, MAX_LENGTH) + ' ...';
46 }
47 return line;
48}
49
50module.exports = function (context) {
51 'use strict';
52
53 var comments = context.getAllComments();
54
55 comments.filter(function (comment) {
56 return isValidCode(comment.value.trim());
57 }).forEach(function (commentedCode) {
58 var code = cut(commentedCode.value.trim());
59 var lines = commentedCode.loc.end.line - commentedCode.loc.start.line + 1;
60 var linesMsg = '(' + lines + ' line' + (lines === 1 ? '' : 's') + ')';
61 context.report({
62 loc: commentedCode.loc
63 }, 'commented out code ' + quote(code) + ' ' + linesMsg);
64 });
65
66 return {};
67};