UNPKG

3.34 kBJavaScriptView Raw
1/**
2 * Created by Rodey on 2016/12/5.
3 */
4
5'use strict';
6const T = require('./tools'),
7 PluginError = require('plugin-error');
8
9function verifyTaskSets(gulp, taskSets, skipArrays) {
10 if (taskSets.length === 0) {
11 throw new Error('No tasks were provided to run-sequence');
12 }
13 let foundTasks = {};
14 taskSets.forEach(function(t) {
15 let isTask = typeof t === 'string',
16 isArray = !skipArrays && Array.isArray(t);
17 if (!isTask && !isArray) {
18 throw new Error('Task ' + t + ' is not a valid task string.');
19 }
20 if (isTask && !gulp.hasTask(t)) {
21 throw new Error('Task ' + t + " is not configured as a task on gulp. If this is a submodule, you may need to use require('run-sequence').use(gulp).");
22 }
23 if (skipArrays && isTask) {
24 if (foundTasks[t]) {
25 throw new Error('Task ' + t + ' is listed more than once. This is probably a typo.');
26 }
27 foundTasks[t] = true;
28 }
29 if (isArray) {
30 if (t.length === 0) {
31 throw new Error('An empty array was provided as a task set');
32 }
33 verifyTaskSets(gulp, t, true, foundTasks);
34 }
35 });
36}
37
38function runSequence(gulp) {
39 if (gulp === undefined) {
40 gulp = require('gulp') || require(T.Path.resolve(__dirname, '../node_modules/gulp/index.js'));
41 }
42
43 // Slice and dice the input to prevent modification of parallel arrays.
44 let taskSets = Array.prototype.slice.call(arguments, 1).map(function(task) {
45 return Array.isArray(task) ? task.slice() : task;
46 }),
47 callBack = typeof taskSets[taskSets.length - 1] === 'function' ? taskSets.pop() : false,
48 currentTaskSet,
49 finish = function(e) {
50 gulp.removeListener('task_stop', onTaskEnd);
51 gulp.removeListener('task_err', onError);
52
53 let error;
54 if (e && e.err) {
55 error = new PluginError('run-sequence(' + e.task + ')', e.err, { showStack: true });
56 }
57
58 if (callBack) {
59 callBack(error);
60 } else if (error) {
61 T.log.red(error.toString());
62 }
63 },
64 onError = function(err) {
65 finish(err);
66 },
67 onTaskEnd = function(event) {
68 let idx = currentTaskSet.indexOf(event.task);
69 if (idx > -1) {
70 currentTaskSet.splice(idx, 1);
71 }
72 if (currentTaskSet.length === 0) {
73 runNextSet();
74 }
75 },
76 runNextSet = function() {
77 if (taskSets.length) {
78 let command = taskSets.shift();
79 if (!Array.isArray(command)) {
80 command = [command];
81 }
82 currentTaskSet = command;
83 gulp.start.apply(gulp, command);
84 } else {
85 finish();
86 }
87 };
88
89 verifyTaskSets(gulp, taskSets);
90
91 gulp.on('task_stop', onTaskEnd);
92 gulp.on('task_err', onError);
93
94 runNextSet();
95}
96
97module.exports = runSequence.bind(null, undefined);
98module.exports.use = function(gulp) {
99 return runSequence.bind(null, gulp);
100};