I want to display files that have more then 3 if/for/while/switch/try statements (same as sonar) so far I have code that traverse the tree and count statements for whole file:
var fs = require('fs');
var esprima = require('esprima');
function traverse(obj, fn) {
for (var key in obj) {
if (obj[key] !== null && fn(obj[key]) === false) {
return false;
}
if (typeof obj[key] == 'object' && obj[key] !== null) {
if (traverse(obj[key], fn) === false) {
return false;
}
}
}
}
fs.readFile(process.argv[2], function(err, file) {
var syntax = esprima.parse(file.toString());
var count = 0;
traverse(syntax, function(obj) {
if (obj.type == "TryStatement" || obj.type == "ForStatement" ||
obj.type == "IfStatement" || obj.type == "WhileStatement"
obj.type == "SwitchStatement") {
count++;
}
});
console.log(process.argv[2] + ' ' + count);
});
How can I count path in the program for instance for this code:
try {
if (foo == 10) {
for (var i=0; i<foo; ++i) {
if (i % 5 == 0) {
var j = i;
while(j--) {
console.log(j);
}
}
}
}
} catch(e) {
if (e instanceof Error) {
if (e.stack) {
console.log(e.stack);
}
}
}
it should show 5 and 2 not 7.