This repository has been archived by the owner on May 12, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
parser.js
99 lines (88 loc) · 2.05 KB
/
parser.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
var fs = require('fs')
, mime = require('mime')
, reader = require('buffered-reader');
function getExtension(path) {
var lastDot = path.lastIndexOf('.');
if (lastDot > -1) {
return path.substring(lastDot + 1);
} else {
return "";
}
}
var codeFileTypes = {
"java": "Java",
"scala": "Scala",
"rb": "Ruby",
"c": "C",
"c++": "C++",
"php": "PHP",
"pl": "Perl",
"js": "JavaScript",
"sh": "Shell",
"cs": "CSharp",
"fs": "FSharp",
"vb": "Visual Basic",
"py": "Python",
"bat": "Batch",
"html": "Html",
"css": "Stylesheets",
"xml": "Xml",
"json": "Json"
};
function getCodeFileType(extension) {
return codeFileTypes[extension];
}
function parseCodeFile(path, filetype, onSuccess) {
var result = {
filetype: filetype,
lines: 0,
codeLines: 0
}
new reader.DataReader(path, { "encoding": "utf-8" })
.on("line", function(line) {
result.lines += 1;
// TODO Better parsing to handle cases such as multi-line comments
var trimmed = line.trim();
if (trimmed.length > 0
&& trimmed.indexOf("#") != 0
&& trimmed.indexOf("//") != 0
&& trimmed.indexOf("/*") != 0) {
result.codeLines += 1;
}
})
.on("end", function() {
onSuccess(result);
})
.read();
}
function parseTextFile(path, onSuccess) {
var result = {
filetype: "Text",
lines: 0,
codeLines: 0
};
// Simply count all lines as non-code lines
new reader.DataReader(path, { "encoding": "utf-8" })
.on("line", function(line) {
result.lines += 1;
})
.on("end", function() {
onSuccess(result);
})
.read();
}
var Parser = {
parse: function(path, onSuccess) {
var extension = getExtension(path);
var codeFileType = getCodeFileType(extension);
if (codeFileType) {
parseCodeFile(path, codeFileType, onSuccess);
} else if (mime.lookup(path).indexOf("text/") == 0) {
parseTextFile(path, onSuccess);
} else {
// unsupported file type
onSuccess(null);
}
}
};
module.exports = Parser;