all files / htmlcs/lib/rules/ max-len.js

100% Statements 39/39
100% Branches 19/19
100% Functions 10/10
100% Lines 39/39
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                            103× 103× 102×     31×   31× 31×     31×   31×       28× 28× 17×     11× 11× 11×   11×             13×     13×     25×                            
/**
 * @file rule: max-len
 * @author chris<wfsr@foxmail.com>
 */
 
module.exports = {
 
    name: 'max-len',
 
    desc: 'Each length of line should be less then the value specified.',
 
    target: 'parser',
 
    lint: function (getCfg, parser, reporter, code) {
 
        var max = getCfg() | 0;
        if (!max) {
            return;
        }
 
        var map = {};
        code.split(/\n/).reduce(function (pos, line) {
            pos.line++;
 
            var len = line.length;
            if (len > max) {
                var item = [];
                item.index = pos.index;
                map[pos.line] = item;
            }
 
            pos.index += len + 1;
 
            return pos;
        }, {index: 0, line: 0});
 
        var line = 1;
 
        function push(type, context) {
            var item = map[line];
            if (!item) {
                return;
            }
 
            var from = context.startIndex;
            var to = context.endIndex;
            var index = item.index + max;
 
            if (index <= from || index > from && index <= to) {
                var last = item[item.length - 1];
                if (!last || last.from !== from) {
                    item.push({type: type, from: from, to: to});
                }
            }
        }
 
        parser.on('comment', function (data) {
            push('#comment', this);
            line += (data.match(/\n/g) || '').length;
        });
 
        parser.on('opentag', function (name) {
            push(name, this);
        });
 
        parser.on('closetag', function (name) {
            push(name, this);
        });
 
        parser.on('text', function (data) {
            line += (data.match(/\n/g) || '').length;
        });
 
        parser.on('end', function () {
            Object.keys(map).forEach(function (line) {
                map[line].forEach(function (node) {
                    reporter.warn(
                        node.from,
                        '048',
                        'Node `' + node.type + '` exceeds the maximum line length of ' + max + '.'
                    );
                });
            });
        });
 
    }
 
};