gulp-function/ts/index.ts

66 lines
2.0 KiB
TypeScript
Raw Normal View History

2016-02-01 02:33:33 +00:00
/// <reference path="typings/main.d.ts" />
import plugins = require("./gulpfunction.plugins");
2015-09-17 20:58:19 +00:00
2015-10-26 15:18:37 +00:00
2016-02-12 04:36:23 +00:00
module.exports = function (functionsToExecuteArg:any|any[],executionModeArg:string = 'forEach') {
2015-11-30 08:49:52 +00:00
//important vars
2016-03-26 16:22:46 +00:00
let executionMode = executionModeArg; //can be forEach or atEnd
let functionsToExecute = functionsToExecuteArg;
let promiseArray = [];
let runFunction = function(functionArg){
let returnValue = functionArg();
if (typeof returnValue !== "undefined" && typeof returnValue.then !== "undefined") {
promiseArray.push(returnValue);
}
2015-11-30 08:49:52 +00:00
};
2016-03-26 16:22:46 +00:00
let checkAndRunFunction = function () {
if (typeof functionsToExecute === "function" ) {
runFunction(functionsToExecute);
} else if (Array.isArray(functionsToExecute)) {
2016-03-26 16:22:46 +00:00
for (let anyFunction in functionsToExecute) {
runFunction(functionsToExecute[anyFunction]);
2015-11-30 08:49:52 +00:00
}
} else {
throw new Error("gulp-callfunction: something is strange with the given arguments");
2015-10-25 21:45:49 +00:00
}
return plugins.Q.all(promiseArray);
2015-11-30 08:49:52 +00:00
};
2015-09-17 20:58:19 +00:00
2016-03-26 16:22:46 +00:00
let hasExecutedOnce = false;
let forEach = function (file, enc, cb) { //the forEach function is called for every chunk
switch (executionMode){
case "forEach":
checkAndRunFunction().then(function(){
cb(null, file);
});
break;
case "forFirst":
!hasExecutedOnce ? checkAndRunFunction().then(function(){
cb(null, file);
}) : cb(null, file);
hasExecutedOnce = true;
break;
case "atEnd":
cb(null, file);
2016-03-26 16:22:46 +00:00
break;
default:
break;
2015-11-30 08:49:52 +00:00
}
};
2015-10-25 21:45:49 +00:00
2016-03-26 16:22:46 +00:00
let atEnd = function(cb) {
if (executionMode === "atEnd") {
checkAndRunFunction().then(function(){
cb();
});
} else {
cb();
2015-11-30 08:49:52 +00:00
}
};
return plugins.through2.obj(forEach,atEnd);
2015-09-17 20:58:19 +00:00
};