-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
106 lines (86 loc) · 2.07 KB
/
index.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
105
106
/**
* Bem-comment
* https://github.com/dpellier/bem-comment
*
* Copyright (c) 2014 Damien Pellier
* Licensed under the MIT license.
*/
var LineByLineReader = require('line-by-line');
var fs = require('fs');
var cli = require('cli');
var commentBuff = {};
var previousLine = '';
var stdout = [];
module.exports = {
processFiles: function() {
cli.args.forEach(function(src) {
processFile(src);
});
}
};
/**
* Read a file and add full class name
* @param {string} src
*/
function processFile(src) {
commentBuff = {};
previousLine = '';
stdout = [];
var lr = new LineByLineReader(src);
lr.on('line', function(line) {
stdout.push(processLine(line));
previousLine = line;
});
lr.on('end', function() {
fs.writeFile(src, stdout.join('\n') + '\n');
});
lr.on('error', function(err) {
throw err;
});
}
/**
* Extract the needed info for class line
* @param {string} line
* @returns {string}
*/
function processLine(line) {
var isClassLine = /^\s*[\.&][^\s]+/gi.test(line);
if (!isClassLine) {
return line;
}
checkPreviousLine();
var spaces = /^\s+/gi.exec(line);
var level = spaces ? spaces[0].length : 0;
var name = line.trim();
// Sub classes need to have a different format
if (level === 0 || name.charAt(0) !== '.') {
name = name.replace(/[\.&\s{]/gi, '');
} else {
name = ' ' + name.replace(/[\.\s{]/gi, '');
}
commentBuff[level] = name;
return buildComment(level) + '\n' + line;
}
/**
* Return the complete class name comment
* @param {number} level
* @returns {string}
*/
function buildComment(level) {
var comment = '\/\/ ';
for (var i = 0; i <= level; i++) {
comment = ' ' + comment;
if (commentBuff[i]) {
comment += commentBuff[i];
}
}
return comment.substr(1);
}
/**
* If the previous line is already a comment, we remove it
*/
function checkPreviousLine() {
if (/^\s*[\/\/]/gi.test(previousLine)) {
stdout.splice(-1);
}
}