all files / htmlcs/lib/rules/ indent-char.js

100% Statements 24/24
100% Branches 13/13
100% Functions 4/4
100% Lines 24/24
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                          103×                               103×   103× 1371× 1371× 1259×       112× 14×       98×   98× 98×   200× 17×             200×           39×                
/**
 * @file rule: indent-char
 * @author nighca<nighca@live.cn>
 */
 
module.exports = {
 
    name: 'indent-char',
 
    desc: 'Line should indent with space(2/4) or tab.',
 
    target: 'parser',
 
    lint: function (getCfg, parser, reporter) {
        var cfgMap = {
            'tab': {
                name: 'tab',
                pattern: /^\t*(?=\S|$)/
            },
            'space-2': {
                name: '2 spaces',
                pattern: /^(  )*(?=\S|$)/
            },
            'space-4': {
                name: '4 spaces',
                pattern: /^(    )*(?=\S|$)/
            }
        };
 
        // exclude-tags
        var excludeTags = ['script', 'style'];
 
        parser.on('text', function (data) {
            var cfg = getCfg();
            if (!cfg) {
                return;
            }
 
            // if should be excluded
            if (excludeTags.indexOf(this._stack[this._stack.length - 1]) >= 0) {
                return;
            }
 
            // get pattern ( use space-4 as default )
            cfg = cfgMap[cfg] || cfgMap['space-4'];
 
            var pos = this.startIndex;
            data.split('\n').forEach(function (line, i) {
                // discard the first line cause it does not start from \n,
                if (i && !cfg.pattern.test(line)) {
                    reporter.warn(
                        pos,
                        '032',
                        'Line should indent with ' + cfg.name + '.'
                    );
                }
 
                pos += line.length + 1;
            });
        });
    },
 
    format: function (getCfg, document, options) {
        switch (getCfg()) {
            case 'tab':
                options['indent-char'] = 'tab';
                break;
            case 'space-2':
                options['indent-char'] = 'space';
                options['indent-size'] = 2;
                break;
            case 'space-4':
                options['indent-char'] = 'space';
                options['indent-size'] = 4;
                break;
        }
    }
 
};