jshint.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * grunt-contrib-jshint
  3. * https://gruntjs.com/
  4. *
  5. * Copyright (c) 2016 "Cowboy" Ben Alman, contributors
  6. * Licensed under the MIT license.
  7. */
  8. 'use strict';
  9. module.exports = function(grunt) {
  10. var path = require('path');
  11. var hooker = require('hooker');
  12. var jshint = require('./lib/jshint').init(grunt);
  13. grunt.registerMultiTask('jshint', 'Validate files with JSHint.', function() {
  14. var done = this.async();
  15. // Merge task-specific and/or target-specific options with these defaults.
  16. var options = this.options({
  17. force: false,
  18. reporter: null,
  19. reporterOutputRelative: true
  20. });
  21. // Report JSHint errors but dont fail the task
  22. var force = options.force;
  23. delete options.force;
  24. // Whether to output the report to a file
  25. var reporterOutput = options.reporterOutput;
  26. // Hook into stdout to capture report
  27. var output = '';
  28. if (reporterOutput) {
  29. hooker.hook(process.stdout, 'write', {
  30. pre: function(out) {
  31. output += out;
  32. return hooker.preempt();
  33. }
  34. });
  35. }
  36. jshint.lint(this.filesSrc, options, function(results, data) {
  37. var failed = 0;
  38. if (results.length > 0) {
  39. // Fail task if errors were logged except if force was set.
  40. failed = force;
  41. if (jshint.usingGruntReporter === true) {
  42. var numErrors = grunt.util._.reduce(results, function(memo, result) {
  43. return memo + (result.error ? 1 : 0);
  44. }, 0);
  45. var numFiles = data.length;
  46. grunt.log.error(numErrors + ' ' + grunt.util.pluralize(numErrors, 'error/errors') + ' in ' +
  47. numFiles + ' ' + grunt.util.pluralize(numFiles, 'file/files'));
  48. }
  49. } else {
  50. if (jshint.usingGruntReporter === true && data.length > 0) {
  51. grunt.log.ok(data.length + ' ' + grunt.util.pluralize(data.length, 'file/files') + ' lint free.');
  52. }
  53. }
  54. // Write the output of the reporter if wanted
  55. if (reporterOutput) {
  56. hooker.unhook(process.stdout, 'write');
  57. reporterOutput = grunt.template.process(reporterOutput);
  58. var destDir = path.dirname(reporterOutput);
  59. if (!grunt.file.exists(destDir)) {
  60. grunt.file.mkdir(destDir);
  61. }
  62. grunt.file.write(reporterOutput, output);
  63. grunt.log.ok('Report "' + reporterOutput + '" created.');
  64. }
  65. done(failed);
  66. });
  67. });
  68. };