index.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. 'use strict';
  2. var fs = require('fs');
  3. var log = require('gulplog');
  4. var stdout = require('mute-stdout');
  5. var taskTree = require('./task-tree');
  6. var copyTree = require('../../shared/log/copy-tree');
  7. var tildify = require('../../shared/tildify');
  8. var logTasks = require('../../shared/log/tasks');
  9. var ansi = require('../../shared/ansi');
  10. var exit = require('../../shared/exit');
  11. var logEvents = require('./log/events');
  12. var logTasksSimple = require('./log/tasks-simple');
  13. var registerExports = require('../../shared/register-exports');
  14. var requireOrImport = require('../../shared/require-or-import');
  15. function execute(opts, env, config) {
  16. var tasks = opts._;
  17. var toRun = tasks.length ? tasks : ['default'];
  18. if (opts.tasksSimple || opts.tasks || opts.tasksJson) {
  19. // Mute stdout if we are listing tasks
  20. stdout.mute();
  21. }
  22. // This is what actually loads up the gulpfile
  23. requireOrImport(env.configPath, function(err, exported) {
  24. // Before import(), if require() failed we got an unhandled exception on the module level.
  25. // So console.error() & exit() were added here to mimic the old behavior as close as possible.
  26. if (err) {
  27. console.error(err);
  28. exit(1);
  29. }
  30. log.info('Using gulpfile', ansi.magenta(tildify(env.configPath)));
  31. var gulpInst = require(env.modulePath);
  32. logEvents(gulpInst);
  33. registerExports(gulpInst, exported);
  34. // Always unmute stdout after gulpfile is required
  35. stdout.unmute();
  36. var tree;
  37. if (opts.tasksSimple) {
  38. return logTasksSimple(env, gulpInst);
  39. }
  40. if (opts.tasks) {
  41. tree = taskTree(gulpInst.tasks);
  42. if (config.description && typeof config.description === 'string') {
  43. tree.label = config.description;
  44. } else {
  45. tree.label = 'Tasks for ' + ansi.magenta(tildify(env.configPath));
  46. }
  47. return logTasks(tree, opts, function(task) {
  48. return gulpInst.tasks[task].fn;
  49. });
  50. }
  51. if (opts.tasksJson) {
  52. tree = taskTree(gulpInst.tasks);
  53. if (config.description && typeof config.description === 'string') {
  54. tree.label = config.description;
  55. } else {
  56. tree.label = 'Tasks for ' + tildify(env.configPath);
  57. }
  58. var output = JSON.stringify(copyTree(tree, opts));
  59. if (typeof opts.tasksJson === 'boolean') {
  60. return console.log(output);
  61. }
  62. return fs.writeFileSync(opts.tasksJson, output, 'utf-8');
  63. }
  64. gulpInst.start.apply(gulpInst, toRun);
  65. });
  66. }
  67. module.exports = execute;