-
Notifications
You must be signed in to change notification settings - Fork 0
/
task-runner.js
115 lines (91 loc) · 1.96 KB
/
task-runner.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
'use strict';
const fs = require('fs');
const taskName = getTaskName(process.argv[2]);
var tasks = {};
module.exports = {
task,
src,
dest,
watch
};
function task(name, tasksBefore = null, taskCallback = null) {
tasks[name] = processTaskArgs(tasksBefore, taskCallback);
if (shouldRunTask(name)) {
runTask(name);
}
}
function src(filePath) {
let fileContent = fs.readFileSync(filePath, 'utf-8');
return {
pipe: bindPipe(fileContent)
}
}
function dest(outputPath) {
return function (content) {
fs.writeFileSync(outputPath, content);
}
}
function watch(filePath, taskName) {
fs.watch(filePath, {encoding: 'buffer'}, function (eventType, fileName) {
if (fileName) {
runTask(taskName);
}
});
}
function bindPipe(content) {
return function (callback) {
return {
pipe: bindPipe(callback(content))
};
}
}
function runTask(name) {
if (isArray(tasks[name]['beforeTasks'])) {
tasks[name].beforeTasks.forEach(taskName => {
runTask(taskName);
});
}
if (tasks[name]['callback']
&& isFunction(tasks[name]['callback'])) {
tasks[name].callback();
}
}
function shouldRunTask(name) {
return require.main !== module &&
name === taskName
}
function processTaskArgs(tasksBefore, taskCallback) {
var beforeTasks = null;
var callback = null;
if (isArray(tasksBefore)) {
beforeTasks = tasksBefore;
}
if (isString(tasksBefore)) {
beforeTasks = tasksBefore.split(' ');
}
if (isFunction(tasksBefore)) {
callback = tasksBefore;
}
if (taskCallback && isFunction(taskCallback)) {
callback = taskCallback;
}
return {
beforeTasks,
callback
}
}
function getTaskName(arg) {
if (arg === 'undefined') {
return 'default';
}
return arg;
}
function isArray(element) {
return element instanceof Array;
}
function isString(element) {
return typeof element === 'string';
}
function isFunction(element) {
return typeof element === 'function';
}