Checking for copyright headers in your source code using GruntJS

The following example shows how you can create a simple GruntJS task to check if your *.js files have a copyright header.

Note: The pattern option in the ‘copyright’ task takes a string or RegExp object.

module.exports = function (grunt) {
  grunt.initConfig({
    copyright: {
      files: [
        "**/*.js",
        "!**/node_modules/**",
        "!web/bundle.min.js"
      ],
      options: {
        pattern: "This Source Code Form is subject to the terms of the Mozilla Public"
      }
    }
  });

  grunt.registerMultiTask('copyright', 'Copyright all the things!', function () {
    var pattern = this.options().pattern;
    var files = this.filesSrc.map(function (file) {
      return {
        "name": file,
        "txt": grunt.file.read(file, "utf8")
      };
    }).filter(function (file) {
      return !file.txt.match(pattern);
    });

    if (files.length) {
      grunt.log.subhead("The following files are missing copyright headers:");
      files.forEach(function (file) {
        grunt.log.warn(file.name);
      });
      return false;
    }
  });

  grunt.registerTask('default', ['copyright']);
};

Leave a Reply

Your email address will not be published.