tasks.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /* jshint node: true, esnext: true */
  2. 'use strict';
  3. const gulp = require( 'gulp' );
  4. const jshint = require( 'gulp-jshint' );
  5. const jscs = require( 'gulp-jscs' );
  6. const fs = require( 'fs' );
  7. const gulpFilter = require( 'gulp-filter' );
  8. const gutil = require( 'gulp-util' );
  9. module.exports = ( config ) => {
  10. const src = [ '**/*.js' ].concat( config.IGNORED_FILES.map( i => '!' + i ), getGitIgnore() );
  11. const tasks = {
  12. /**
  13. * Returns stream containing jshint and jscs reporters.
  14. *
  15. * @returns {Stream}
  16. */
  17. lint() {
  18. return gulp.src( src )
  19. .pipe( lint() );
  20. },
  21. /**
  22. * This method is executed on pre-commit hook, linting only files staged for current commit.
  23. *
  24. * @returns {Stream}
  25. */
  26. lintStaged() {
  27. const guppy = require( 'git-guppy' )( gulp );
  28. return guppy.stream( 'pre-commit', { base: './' } )
  29. .pipe( gulpFilter( src ) )
  30. .pipe( lint() )
  31. // Error reporting for gulp.
  32. .pipe( jscs.reporter( 'fail' ) )
  33. .on( 'error', errorHandler )
  34. .pipe( jshint.reporter( 'fail' ) )
  35. .on( 'error', errorHandler );
  36. /**
  37. * Handles error from jscs and jshint fail reporters. Stops node process with error code
  38. * and prints error message to the console.
  39. */
  40. function errorHandler() {
  41. gutil.log( gutil.colors.red( 'Linting failed, commit aborted' ) );
  42. process.exit( 1 );
  43. }
  44. },
  45. register() {
  46. gulp.task( 'lint', tasks.lint );
  47. gulp.task( 'lint-staged', tasks.lintStaged );
  48. }
  49. };
  50. return tasks;
  51. /**
  52. * Gets the list of ignores from `.gitignore`.
  53. *
  54. * @returns {String[]} The list of ignores.
  55. */
  56. function getGitIgnore( ) {
  57. let gitIgnoredFiles = fs.readFileSync( '.gitignore', 'utf8' );
  58. return gitIgnoredFiles
  59. // Remove comment lines.
  60. .replace( /^#.*$/gm, '' )
  61. // Transform into array.
  62. .split( /\n+/ )
  63. // Remove empty entries.
  64. .filter( ( path ) => !!path )
  65. // Add `!` for ignore glob.
  66. .map( i => '!' + i );
  67. }
  68. /**
  69. * Returns stream with all linting plugins combined.
  70. *
  71. * @returns {Stream}
  72. */
  73. function lint() {
  74. const stream = jshint();
  75. stream
  76. .pipe( jscs() )
  77. .pipe( jscs.reporter() )
  78. .pipe( jshint.reporter( 'jshint-reporter-jscs' ) );
  79. return stream;
  80. }
  81. };