tools.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /* jshint node: true */
  2. 'use strict';
  3. var dirtyFiles,
  4. ignoreList;
  5. module.exports = {
  6. checkTaskInQueue: function( grunt, task ) {
  7. var cliTasks = grunt.cli.tasks;
  8. // Check if the task has been called directly.
  9. var isDirectCall = ( cliTasks.indexOf( task ) > -1 );
  10. // Check if this is a "default" call and that the task is inside "default".
  11. var isDefaultTask = ( cliTasks.indexOf( 'default' ) > -1 ) || !cliTasks.length,
  12. // Hacking grunt hard.
  13. isTaskInDefault = isDefaultTask && ( grunt.task._tasks.default.info.indexOf( '"' + task + '"' ) > -1 );
  14. return isDirectCall || isTaskInDefault;
  15. },
  16. setupMultitaskConfig: function( grunt, options ) {
  17. var that = this,
  18. task = options.task,
  19. taskConfig = {},
  20. config = taskConfig[ task ] = {
  21. options: options.defaultOptions
  22. };
  23. // "all" is the default target to be used if others are not to be run.
  24. var all = options.targets.all,
  25. isAll = true;
  26. delete options.targets.all;
  27. Object.getOwnPropertyNames( options.targets ).forEach( function( target ) {
  28. if ( that.checkTaskInQueue( grunt, task + ':' + target ) ) {
  29. config[ target ] = options.targets[ target ]();
  30. isAll = false;
  31. }
  32. } );
  33. if ( isAll ) {
  34. config.all = all();
  35. }
  36. // Merge over configurations set in gruntfile.js.
  37. grunt.config.merge( taskConfig );
  38. },
  39. getGitIgnore: function( grunt ) {
  40. if ( !ignoreList ) {
  41. ignoreList = grunt.file.read( '.gitignore' );
  42. ignoreList = ignoreList
  43. // Remove comment lines.
  44. .replace( /^#.*$/gm, '' )
  45. // Transform into array.
  46. .split( /\n+/ )
  47. // Remove empty entries.
  48. .filter( function( path ) {
  49. return !!path;
  50. } );
  51. }
  52. return ignoreList;
  53. },
  54. getGitDirtyFiles: function() {
  55. // Cache it, so it is executed only once when running multiple tasks.
  56. if ( !dirtyFiles ) {
  57. dirtyFiles = this.shExec( 'git diff-index --name-only HEAD' ).replace( /\s*$/, '' ).split( '\n' );
  58. if ( dirtyFiles.length == 1 && !dirtyFiles[ 0 ] ) {
  59. dirtyFiles = [];
  60. }
  61. }
  62. return dirtyFiles;
  63. },
  64. shExec: function( command ) {
  65. var sh = require( 'shelljs' );
  66. sh.config.silent = true;
  67. var ret = sh.exec( command );
  68. if ( ret.code ) {
  69. throw new Error(
  70. 'Error while executing `' + command + '`:\n\n' +
  71. ret.output
  72. );
  73. }
  74. return ret.output;
  75. }
  76. };