Checking code for risky comments

Kim T
Creative Technology Concepts & Code
2 min readOct 17, 2018
Risk Code Tool

When you work on a large platform or product, you can have multiple developers and thousands of lines of code.

It becomes very difficult to monitor all the code added, and also to ensure the comments are written well. At the end of a project, you may need to hand over the code to a third-party or client. This usually requires reviewing the code to ensure it follows best practices.

Checking code quality is a fairly straightforward approach, using unit/functional tests for testing functionality and linting for code formatting. But the difficulty is how to solve developers putting negative or risky comments in the code?

For a recent project I started to read through comments one-by-one, but after only reaching a thousand lines I was sure there was a better way. I looked for tools which could detect bad words, but didn’t seem to be any good ones.

I embarqued on a journey to build a risky code detection tool, which would work similarly to a testing tool:
- scan all files
- check for bad words using sentiment analysis
- output a list of results, with line numbers to fix them

1) To start we need to loop through all files we want to scan, and return promises (this means they can resolve at different times):

pattern = 'examples/**/*(*.js|*.css|*.scss|*.html|*.py)';glob(pattern, function (error, paths) {
paths.forEach(function(path, index) {
promises.push(new Promise((resolve) => {
// do something
});
}))
});

2) Then inside the promise we want to load each file line-by-line, and run sentiment analysis on it:

var readline = require('readline');
var Sentiment = require('sentiment');
var sentiment = new Sentiment();
var file = {
lines: []
};
var lineReader = readline.createInterface({
input: fs.createReadStream(path)
});
lineReader.on('line', function(line) {
file.lines.push(sentiment.analyze(line));
});
lineReader.on('close', function() {
resolve(file);
});

3) Then last step is to wait for all promises to resolve and log out the results:

Promise.all(promises).then(function(results) {
results.forEach(function(file) {
file.lines.forEach(function(line) {
console.log(line);
});
});
});

I’ve added some additional features such as traffic-light highlighting for good, medium and bad results, and some metrics for files scanned. I also turned it into a cli-tool so a user can install & run it from the command line using:

risk --path='examples/**/*(*.js|*.css|*.scss|*.html|*.py)' --log=-3

Check out the tool here:
https://github.com/kmturley/risk-code-tool

Submit your issues/feedback/ideas so we can make it better :)

--

--

Kim T
Creative Technology Concepts & Code

Creative Technologist, coder, music producer, and bike fanatic. I find creative uses for technology.