-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
77 lines (64 loc) · 2.02 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
#!/usr/bin/env node
var config = require("./config.json"),
fs = require("fs"),
path = require("path"),
isUtf8 = require('is-utf8'),
buffer = require("buffer").Buffer;
var commentContent = fs.readFileSync(path.join(__dirname,"comment_default.txt"),{encoding:"utf8"});
var commentContent_forUTF8 = fs.readFileSync(path.join(__dirname,"comment_default_utf8.txt"),{encoding:"utf8"});
console.log("comment template is at :" + __dirname + "\r\njust rewrite it as you wish\r\n");
var targetList = process.argv;
if(targetList[0] == "node"){
targetList.shift();
}
targetList.shift();
if(targetList.length <= 0){
console.log("usage : loveNote fileA [fileB [fileC]..]");
console.log("usage : loveNote dirName");
process.exit(0);
}
for(var i = 0 ; i < targetList.length ; i++){
var target = targetList[i],
stat = fs.statSync(target);
if(stat.isFile()){
matchRuleForFile(target);
}
if(stat.isDirectory()){
var list = fs.readdirSync(target);
list.forEach(function(item){
matchRuleForFile(path.join(target,item));
});
}
}
function matchRuleForFile(filePath){
//traverse rules
for (var i = 0 ; i < config.length ; i++){
var configItem = config[i];
var reg = new RegExp(config[i].tail);
if(reg.test(filePath)){
dealFile(filePath);
break;
}
}
function dealFile(filePath) {
if(!fs.existsSync(filePath)){
console.log("file not exist :" + filePath);
}else{
fs.readFile(filePath,function(err,data){
if(err) throw err;
//add comment prefix
var commentData = isUtf8(data) ? commentContent_forUTF8 : commentContent;
var lineArr = commentData.split("\n");
lineArr.forEach(function(line,index){
lineArr[index] = configItem.prefix + line;
});
var currentComment = new Buffer(lineArr.join("\n") + "\n"); //TODO :cache this result
process.stdout.write("--> " + filePath + "...");
var finalResult = buffer.concat([currentComment,data]);
fs.unlinkSync(filePath);
fs.writeFileSync(filePath,finalResult)
process.stdout.write("done\r\n");
});
}
}
}