tasks.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 guppy = require( 'git-guppy' )( gulp );
  8. const gulpFilter = require( 'gulp-filter' );
  9. const gutil = require( 'gulp-util' );
  10. module.exports = ( config ) => {
  11. const src = [ '**/*.js' ].concat( config.IGNORED_FILES.map( i => '!' + i ), getGitIgnore() );
  12. gulp.task( 'lint', () => {
  13. return gulp.src( src )
  14. .pipe( lint() );
  15. } );
  16. gulp.task( 'pre-commit', () => {
  17. return guppy.stream( 'pre-commit' )
  18. .pipe( gulpFilter( src ) )
  19. .pipe( lint() )
  20. // Error reporting for gulp.
  21. .pipe( jscs.reporter( 'fail' ) )
  22. .on( 'error', errorHandler )
  23. .pipe( jshint.reporter( 'fail' ) )
  24. .on( 'error', errorHandler );
  25. /**
  26. * Handles error from jscs and jshint fail reporters. Stops node process with error code
  27. * and prints error message to the console.
  28. */
  29. function errorHandler() {
  30. gutil.log( gutil.colors.red( 'Linting failed, commit aborted' ) );
  31. process.exit( 1 );
  32. }
  33. } );
  34. /**
  35. * Gets the list of ignores from `.gitignore`.
  36. *
  37. * @returns {String[]} The list of ignores.
  38. */
  39. function getGitIgnore( ) {
  40. let gitIgnoredFiles = fs.readFileSync( '.gitignore', 'utf8' );
  41. return gitIgnoredFiles
  42. // Remove comment lines.
  43. .replace( /^#.*$/gm, '' )
  44. // Transform into array.
  45. .split( /\n+/ )
  46. // Remove empty entries.
  47. .filter( ( path ) => !!path )
  48. // Add `!` for ignore glob.
  49. .map( i => '!' + i );
  50. }
  51. /**
  52. * Returns stream with all linting plugins combined.
  53. * @returns { Stream }
  54. */
  55. function lint() {
  56. const stream = jscs();
  57. stream
  58. .pipe( jshint() )
  59. .pipe( jscs.reporter() )
  60. .pipe( jshint.reporter( 'jshint-reporter-jscs' ) );
  61. return stream;
  62. }
  63. };