tools.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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 task = options.task,
  18. taskConfig = {},
  19. config = taskConfig[ task ] = {
  20. options: options.defaultOptions
  21. };
  22. // "all" is the default target to be used if others are not to be run.
  23. var all = options.targets.all,
  24. isAll = true;
  25. delete options.targets.all;
  26. Object.getOwnPropertyNames( options.targets ).forEach( function( target ) {
  27. if ( this.checkTaskInQueue( grunt, task + ':' + target ) ) {
  28. config[ target ] = options.targets[ target ]();
  29. isAll = false;
  30. }
  31. }, this );
  32. if ( isAll ) {
  33. config.all = all();
  34. }
  35. // Merge over configurations set in gruntfile.js.
  36. grunt.config.merge( taskConfig );
  37. },
  38. getGitIgnore: function( grunt ) {
  39. if ( !ignoreList ) {
  40. ignoreList = grunt.file.read( '.gitignore' );
  41. ignoreList = ignoreList
  42. // Remove comment lines.
  43. .replace( /^#.*$/gm, '' )
  44. // Transform into array.
  45. .split( /\n+/ )
  46. // Remove empty entries.
  47. .filter( function( path ) {
  48. return !!path;
  49. } );
  50. }
  51. return ignoreList;
  52. },
  53. getGitDirtyFiles: function() {
  54. // Cache it, so it is executed only once when running multiple tasks.
  55. if ( !dirtyFiles ) {
  56. dirtyFiles = this
  57. // Compare the state of index with HEAD.
  58. .shExec( 'git diff-index --name-only HEAD' )
  59. // Remove trailing /n, to avoid empty entry.
  60. .replace( /\s*$/, '' )
  61. // Transform into array.
  62. .split( '\n' );
  63. // If nothing is returned, the array will one one empty string only.
  64. if ( dirtyFiles.length == 1 && !dirtyFiles[ 0 ] ) {
  65. dirtyFiles = [];
  66. }
  67. }
  68. return dirtyFiles;
  69. },
  70. shExec: function( command ) {
  71. var sh = require( 'shelljs' );
  72. sh.config.silent = true;
  73. var ret = sh.exec( command );
  74. if ( ret.code ) {
  75. throw new Error(
  76. 'Error while executing `' + command + '`:\n\n' +
  77. ret.output
  78. );
  79. }
  80. return ret.output;
  81. }
  82. };