Using the dba module in a #GruntJS task

The following example shows how you can create a simple Grunt task wrapper for the Node.js dba module.

DBA is an experimental tool which is trying to determine a complex JS functions with very low comments / logical lines of code ratio.

Install the required dev dependencies and save them to our package.json file:

$ npm i grunt dba lodash.template -D

Next, enter the following task into your Grunt tasks folder:

#!/usr/bin/env node

var path = require('path');

var dba = require('dba');
var _ = {
  template: require('lodash.template')
};

module.exports = function (grunt) {
  'use strict';

  grunt.config('dba', {
    app: {
      options: {
        effort: 2000,
        ratio: 0
      },
      src: [
        '**/*.js',
        '!node_modules/**'
      ]
    }
  });

  grunt.registerMultiTask('dba', 'Seriously, just comment your code.', function () {
    var options = this.options() || {};
    options.format = options.format || '- [${file}:${line}] ${name}() -> ${effort}';
    var _tmpl = _.template(options.format);

    var files = this.filesSrc.filter(function (file) {
      // Make sure its actually a file and not a folder named `foo.js`.
      return grunt.file.isFile(file);
    });

    var results = [];

    files.forEach(function (file) {
      var content = grunt.file.read(file, 'utf8');
      var arr;
      try {
        arr = dba(content, options);
        // If we got results from `dba` log the to the results array and set the
        // `success` flag to fail the build.
        if (arr.length > 0) {
          arr = arr.map(function (item) {
            // Remap some data to make it easier to template.
            item.file = path.basename(file);
            item.effort = parseInt(item.effort, 10);
            return item;
          });
          results.push({'file': file, 'messages': arr});
        }
      } catch (err) {
        grunt.verbose.writeln('Unable to parse %s', file);
      }
    });

    if (results.length > 0) {
      results.forEach(function (result) {
        grunt.log.subhead(result.file);
        result.messages.forEach(function (message) {
          grunt.log.writeln(_tmpl(message));
        });
      });
      return false;
    }
  });
};

This Week in #GruntJS (2013-11-29)

@NodeJS Updates

@npmjs Updates

@GruntJS Updates

Continue reading

This Week in #GruntJS (2013-11-22)

@NodeJS Updates

@npmjs Updates

@gruntjs Updates

Continue reading

This Week in #GruntJS (2013-11-15)

@Nodejs Updates

@npmjs Updates

  • Hi! I’m the @npmjs mirror for Europe. http://npmjs.eu Come check me out! (src)
  • @npmjs tip: You can now use the GitHub shorthand to define repository in your package.json: “repository”: “sindresorhus/chalk” (src)

@GruntJS Updates

Continue reading

This Week in #GruntJS (2013-11-08)

#GruntJS Articles

Continue reading

This Week in #GruntJS (2013-11-01)

@Nodejs Updates

@GruntJS Updates

Continue reading