8
0

tasks.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. const tasks = {
  13. /**
  14. * Returns stream containing jshint and jscs reporters.
  15. *
  16. * @returns {Stream}
  17. */
  18. lint() {
  19. return gulp.src( src )
  20. .pipe( lint() );
  21. },
  22. /**
  23. * This method is executed on pre-commit hook, linting only files staged for current commit.
  24. *
  25. * @returns {Stream}
  26. */
  27. lintStaged() {
  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. };
  46. gulp.task( 'lint', tasks.lint );
  47. gulp.task( 'lint-staged', tasks.lintStaged );
  48. return tasks;
  49. /**
  50. * Gets the list of ignores from `.gitignore`.
  51. *
  52. * @returns {String[]} The list of ignores.
  53. */
  54. function getGitIgnore( ) {
  55. let gitIgnoredFiles = fs.readFileSync( '.gitignore', 'utf8' );
  56. return gitIgnoredFiles
  57. // Remove comment lines.
  58. .replace( /^#.*$/gm, '' )
  59. // Transform into array.
  60. .split( /\n+/ )
  61. // Remove empty entries.
  62. .filter( ( path ) => !!path )
  63. // Add `!` for ignore glob.
  64. .map( i => '!' + i );
  65. }
  66. /**
  67. * Returns stream with all linting plugins combined.
  68. *
  69. * @returns {Stream}
  70. */
  71. function lint() {
  72. const stream = jshint();
  73. stream
  74. .pipe( jscs() )
  75. .pipe( jscs.reporter() )
  76. .pipe( jshint.reporter( 'jshint-reporter-jscs' ) );
  77. return stream;
  78. }
  79. };