提到前端工程的自動化構建,gulp是其中很重要的一個工具,gulp是一種基於stream的前端構建工具,相比於grunt使用臨時文件的策略,會有較大的速度優點。本文會對gulp的主要部分進行詳細剖析,期待本文可以幫助讀者更好地在工程中實踐gulp。javascript
gulp等前端構建腳本並非一種全新的思想,早在幾十年前,gnu make已經在各類流行語言中風靡,並解決了相關的各類問題,能夠簡單的認爲gulp是JavaScript語言的「make」。前端
gulp其中兩大核心模塊,任務管理和文件java
本文經過對Orchestrator任務管理模塊的源碼進行分析,理清gulp是如何進行任務管理的。node
經過查看gulp源碼(3.x及以前的版本),能夠看到,gulp全部任務管理相關的功能都是直接從Orchestrator模塊繼承的,並且能夠發現gulp官網對相關任務管理接口的描述,和Orchestrator模塊的描述幾乎徹底同樣。git
// gulp/index.js
...
var Orchestrator = require('orchestrator');
...
function Gulp() { // 構造函數直接調用Orchestrator
Orchestrator.call(this);
}
util.inherits(Gulp, Orchestrator); // 從Orchestrator繼承而來
Gulp.prototype.task = Gulp.prototype.add; // task方法直接使用Orchestrator中的add
...複製代碼
因此下面就一塊兒來分析一下Orchestrator模塊。github
Orchestrator github主頁中對自身的描述gulp
A module for sequencing and executing tasks and dependencies in maximum concurrency.數組
簡單翻譯就是promise
一個可以以最大併發性對任務及其依賴任務進行排序執行的模塊。併發
Orchestrator模塊主要就是添加管理執行任務,並對任務的執行提供異步支持,分別對應
add - 添加任務
add用於添加任務,傳入任務task的名字,依賴數組,以及任務回調函數。
orchestrator中使用核心屬性tasks對象保存各個任務
start - 執行任務
start用於執行以前定義的任務,若是傳入多個任務,start會進行合併,依次放入到任務數組,而後對任務數組序列按照依賴關係進行去重排序,最終對排序的任務數組依次執行
下面是具備完整註釋的源碼。
// Orchestrator/index.js
/*jshint node:true */
"use strict";
var util = require('util');
var events = require('events');
var EventEmitter = events.EventEmitter;
var runTask = require('./lib/runTask');
/* 構造函數裏面 首先調用node中事件模塊的構造函數EventEmitter, EventEmitter.call(this); 這是一種典型的用法,直接掛載Event模塊實例屬性及方法。 接下來初始化了Orchestrator最核心的幾個屬性: doneCallback 是全部任務執行完成後的回調 seq 是排序後的任務隊列,對任務及其依賴的排序是經過seqencify模塊進行的,後面會介紹。 tasks 保存了全部定義的任務,經過add原型方法添加任務。 isRunning 標識當前是否有任務正在執行 */
var Orchestrator = function () {
EventEmitter.call(this);
this.doneCallback = undefined; // call this when all tasks in the queue are done
this.seq = []; // the order to run the tasks
this.tasks = {}; // task objects: name, dep (list of names of dependencies), fn (the task to run)
this.isRunning = false; // is the orchestrator running tasks? .start() to start, .stop() to stop
};
/* * 繼承Event模塊 */
util.inherits(Orchestrator, EventEmitter);
/* * 重置Orchestrator模塊,即重置orchestrator實例的相應狀態和屬性 */
Orchestrator.prototype.reset = function () {
if (this.isRunning) {
this.stop(null);
}
this.tasks = {};
this.seq = [];
this.isRunning = false;
this.doneCallback = undefined;
return this;
};
/* add前面主要是對參數進行了一些校驗檢測,最後將任務task的名字,依賴,回調添加到核心屬性tasks中 */
Orchestrator.prototype.add = function (name, dep, fn) {
if (!fn && typeof dep === 'function') {
fn = dep;
dep = undefined;
}
dep = dep || [];
fn = fn || function () {}; // no-op
if (!name) {
throw new Error('Task requires a name');
}
// validate name is a string, dep is an array of strings, and fn is a function
if (typeof name !== 'string') {
throw new Error('Task requires a name that is a string');
}
if (typeof fn !== 'function') {
throw new Error('Task '+name+' requires a function that is a function');
}
if (!Array.isArray(dep)) {
throw new Error('Task '+name+' can\'t support dependencies that is not an array of strings');
}
dep.forEach(function (item) {
if (typeof item !== 'string') {
throw new Error('Task '+name+' dependency '+item+' is not a string');
}
});
this.tasks[name] = {
fn: fn,
dep: dep,
name: name
};
return this;
};
/* 若是隻給了task的名字,則直接獲取以前定義task,不然經過add添加新的task */
Orchestrator.prototype.task = function (name, dep, fn) {
if (dep || fn) {
// alias for add, return nothing rather than this
this.add(name, dep, fn);
} else {
return this.tasks[name];
}
};
/* 判斷是否已經定義了某個task */
Orchestrator.prototype.hasTask = function (name) {
return !!this.tasks[name];
};
/* * 開始運行任務 * 首先會判斷傳入參數最後一個是否爲函數,若是是,則做爲全部任務 * 結束後的回調,不然也會將其當作一個任務 * * 依次循環收集最後一個參數以前的全部參數(若是最後一個參數不是 * 函數,也將其收集),放入任務數組; * * 對任務數組序列按照依賴關係進行去重排序 * * 調用runStep依次執行排序後的任務數組 */
Orchestrator.prototype.start = function() {
var args, arg, names = [], lastTask, i, seq = [];
args = Array.prototype.slice.call(arguments, 0);
if (args.length) {
lastTask = args[args.length-1];
if (typeof lastTask === 'function') {
this.doneCallback = lastTask;
args.pop();
}
for (i = 0; i < args.length; i++) {
arg = args[i];
if (typeof arg === 'string') {
names.push(arg);
} else if (Array.isArray(arg)) {
names = names.concat(arg); // FRAGILE: ASSUME: it's an array of strings
} else {
throw new Error('pass strings or arrays of strings');
}
}
}
if (this.isRunning) {
// reset specified tasks (and dependencies) as not run
this._resetSpecificTasks(names);
} else {
// reset all tasks as not run
this._resetAllTasks();
}
if (this.isRunning) {
// if you call start() again while a previous run is still in play
// prepend the new tasks to the existing task queue
names = names.concat(this.seq);
}
if (names.length < 1) {
// run all tasks
for (i in this.tasks) {
if (this.tasks.hasOwnProperty(i)) {
names.push(this.tasks[i].name);
}
}
}
seq = [];
try {
this.sequence(this.tasks, names, seq, []);
} catch (err) {
// Is this a known error?
if (err) {
/* sequencify模塊會根據如下兩種不一樣狀況拋出異常, * 一種爲任務未定義;另外一種爲任務序列出現循環依賴 */
if (err.missingTask) {
this.emit('task_not_found', {message: err.message, task:err.missingTask, err: err});
}
if (err.recursiveTasks) {
this.emit('task_recursion', {message: err.message, recursiveTasks:err.recursiveTasks, err: err});
}
}
this.stop(err);
return this;
}
this.seq = seq;
this.emit('start', {message:'seq: '+this.seq.join(',')});
if (!this.isRunning) {
this.isRunning = true;
}
this._runStep();
return this;
};
/* 中止orchestrator實例,根據結束類型的不一樣,拋出不一樣的消息 * 若是定義了回調,則執行回調 */
Orchestrator.prototype.stop = function (err, successfulFinish) {
this.isRunning = false;
if (err) {
this.emit('err', {message:'orchestration failed', err:err});
} else if (successfulFinish) {
this.emit('stop', {message:'orchestration succeeded'});
} else {
// ASSUME
err = 'orchestration aborted';
this.emit('err', {message:'orchestration aborted', err: err});
}
if (this.doneCallback) {
// Avoid calling it multiple times
this.doneCallback(err);
} else if (err && !this.listeners('err').length) {
// No one is listening for the error so speak louder
throw err;
}
};
/* * 引入任務及其依賴任務的排序模塊 */
Orchestrator.prototype.sequence = require('sequencify');
/* 簡單的循環判斷是否全部的任務都已經執行完畢 */
Orchestrator.prototype.allDone = function () {
var i, task, allDone = true; // nothing disputed it yet
for (i = 0; i < this.seq.length; i++) {
task = this.tasks[this.seq[i]];
if (!task.done) {
allDone = false;
break;
}
}
return allDone;
};
/* * 重置task,重置相應的狀態和屬性 */
Orchestrator.prototype._resetTask = function(task) {
if (task) {
if (task.done) {
task.done = false;
}
delete task.start;
delete task.stop;
delete task.duration;
delete task.hrDuration;
delete task.args;
}
};
/* * 循環遍歷重置全部的task */
Orchestrator.prototype._resetAllTasks = function() {
var task;
for (task in this.tasks) {
if (this.tasks.hasOwnProperty(task)) {
this._resetTask(this.tasks[task]);
}
}
};
/* * 循環遍歷重置task,並遞歸重置所依賴的task */
Orchestrator.prototype._resetSpecificTasks = function (names) {
var i, name, t;
if (names && names.length) {
for (i = 0; i < names.length; i++) {
name = names[i];
t = this.tasks[name];
if (t) {
this._resetTask(t);
if (t.dep && t.dep.length) {
this._resetSpecificTasks(t.dep); // recurse
}
//} else {
// FRAGILE: ignore that the task doesn't exist
}
}
}
};
/* 逐個運行任務,當全部任務都結束後,中止orchestrator實例 */
Orchestrator.prototype._runStep = function () {
var i, task;
if (!this.isRunning) {
return; // user aborted, ASSUME: stop called previously
}
for (i = 0; i < this.seq.length; i++) {
task = this.tasks[this.seq[i]];
if (!task.done && !task.running && this._readyToRunTask(task)) {
this._runTask(task);
}
if (!this.isRunning) {
return; // task failed or user aborted, ASSUME: stop called previously
}
}
if (this.allDone()) {
this.stop(null, true);
}
};
/* 判斷當前任務是否能運行,循環判斷其全部依賴任務是否運行結束, * 只要有一個未定義或未結束,則不能運行 */
Orchestrator.prototype._readyToRunTask = function (task) {
var ready = true, // no one disproved it yet
i, name, t;
if (task.dep.length) {
for (i = 0; i < task.dep.length; i++) {
name = task.dep[i];
t = this.tasks[name];
if (!t) {
// FRAGILE: this should never happen
this.stop("can't run "+task.name+" because it depends on "+name+" which doesn't exist");
ready = false;
break;
}
if (!t.done) {
ready = false;
break;
}
}
}
return ready;
};
/* 設置任務的執行時間,重置任務的運行和結束標記 */
Orchestrator.prototype._stopTask = function (task, meta) {
task.duration = meta.duration;
task.hrDuration = meta.hrDuration;
task.running = false;
task.done = true;
};
/* 中止任務後收集相關的參數(任務名字,執行時間,類型,是否正常結束等拋出消息 */
Orchestrator.prototype._emitTaskDone = function (task, message, err) {
if (!task.args) {
task.args = {task:task.name};
}
task.args.duration = task.duration;
task.args.hrDuration = task.hrDuration;
task.args.message = task.name+' '+message;
var evt = 'stop';
if (err) {
task.args.err = err;
evt = 'err';
}
// 'task_stop' or 'task_err'
this.emit('task_'+evt, task.args);
};
/* * 開始運行任務,並添加任務屬性,args,running等 * 最終經過runTask完成任務回調的執行並最終結束任務 * runTask接受任務的回調,以及function(err, meta){...}回調函數爲參數 * gulp.task文檔中聲稱對異步任務的支持,正是在runTask中完成的 * runTask中首先會執行任務的回調函數 * * 第一種對異步支持的方式能夠經過向任務回調函數傳入一個callback, * 執行callback就會調用runTask傳入的第二個回調函數參數,進而結束任務 * * 其餘方式,若是沒有傳入callback,runTask中會對任務回調函數的執行 * 結果進行三種判斷,分別爲promise,stream流,以及正常同步函數; * 對於promise和stream流,一樣屬於異步任務,promise會在其resolve/rejected * 後,調用runTask的第二個回調參數,結束任務;對於stream流,則會在 * 流結束時刻調用runTask的第二個回調參數,結束任務; * * 對於正常同步函數,則直接調用runTask的第二個回調參數,結束任務 */
Orchestrator.prototype._runTask = function (task) {
var that = this;
task.args = {task:task.name, message:task.name+' started'};
this.emit('task_start', task.args);
task.running = true;
runTask(task.fn.bind(this), function (err, meta) {
that._stopTask.call(that, task, meta);
that._emitTaskDone.call(that, task, meta.runMethod, err);
if (err) {
return that.stop.call(that, err);
}
that._runStep.call(that);
});
};
// FRAGILE: ASSUME: this list is an exhaustive list of events emitted
var events = ['start','stop','err','task_start','task_stop','task_err','task_not_found','task_recursion'];
var listenToEvent = function (target, event, callback) {
target.on(event, function (e) {
e.src = event;
callback(e);
});
};
/* 監聽events中全部類型的函數 */
Orchestrator.prototype.onAll = function (callback) {
var i;
if (typeof callback !== 'function') {
throw new Error('No callback specified');
}
for (i = 0; i < events.length; i++) {
listenToEvent(this, events[i], callback);
}
};
module.exports = Orchestrator;複製代碼
sequencify模塊主要完成的工做就是針對一個給定的任務數組序列,分析依賴關係,最終給出一個按照任務依賴順序排列的任務數組序列,而後依次執行各個任務
// sequencify/index.js
/*jshint node:true */
"use strict";
/* * 四個輸入參數 * tasks: 當前定義的全部任務 * names: 須要進行依賴分析的任務數組序列 * results: 最終獲得的按照任務依賴順序排列的任務數組序列, * 而且這個任務序列是去重的 * nest: 記錄當前任務所處的依賴層次路徑,好比taskA依賴taskB, * taskB依賴taskC,則分析完taskA後,按照依賴關係,對 * taskB分析的時候,nest即爲['taskA'],進一步,當分析 * taskC時,nest爲['taskA', 'taskB'],藉此來進行判斷是 * 否有循環依賴。即,若是分析一個任務時,若是其自身在 * nest存在,即存在循環依賴,則中斷分析,拋出異常。 */
var sequence = function (tasks, names, results, nest) {
var i, name, node, e, j;
nest = nest || [];
for (i = 0; i < names.length; i++) {
name = names[i];
// de-dup results
/* 任務序列去重 */
if (results.indexOf(name) === -1) {
node = tasks[name];
if (!node) {
/* 任務不存在則拋出異常 */
e = new Error('task "'+name+'" is not defined');
e.missingTask = name;
e.taskList = [];
for (j in tasks) {
if (tasks.hasOwnProperty(j)) {
e.taskList.push(tasks[j].name);
}
}
throw e;
}
if (nest.indexOf(name) > -1) {
/* 任務序列存在循環依賴,拋出異常 */
nest.push(name);
e = new Error('Recursive dependencies detected: '+nest.join(' -> '));
e.recursiveTasks = nest;
e.taskList = [];
for (j in tasks) {
if (tasks.hasOwnProperty(j)) {
e.taskList.push(tasks[j].name);
}
}
throw e;
}
if (node.dep.length) {
nest.push(name);
sequence(tasks, node.dep, results, nest); // recurse
nest.pop(name);
}
results.push(name);
}
}
};
module.exports = sequence;複製代碼
對於gulp 4.x以後的版本,gulp更換了任務管理的模塊爲undertaker,後續文章中會對其進一步分析,並與orchestrator進行必定的對比。
接下來的系列文章會對gulp中的stream流管理進行分析。
By Hong