-
Notifications
You must be signed in to change notification settings - Fork 15
/
index.js
86 lines (71 loc) · 1.96 KB
/
index.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
'use strict';
var fs = require('fs');
var path = require('path');
var gulp = require('gulp');
var assign = require('object-assign');
function isString(str) {
return 'string' === typeof str;
}
function getExtensions() {
return Object.keys(require.extensions);
}
function getDefaults() {
return {
dir: 'gulp-tasks',
exts: getExtensions() || ['.js']
};
}
function cleanDir(options) {
if (!options.dir) return;
options.dir = options.dir
.replace(/^\.\//, '')
.replace(/\/$/, '');
}
module.exports = function(options) {
if (isString(options)) {
options = { dir: options };
}
if (options) {
cleanDir(options);
}
var opts = assign(getDefaults(), options);
function byExtension(fileName) {
var extension = path.extname(fileName);
return ~opts.exts.indexOf(extension);
}
function stripExtension(fileName) {
var extension = path.extname(fileName);
return path.basename(fileName, extension);
}
function loadTask(parents, task) {
var modulePath = path.join(process.cwd(), opts.dir, parents.join(path.sep) || '', task);
var func = require(modulePath);
var dependencies = func.dependencies || [];
var taskName = stripExtension(task);
var context = {
gulp: gulp,
opts: opts
};
// If subtask -> namespace: "parent:child"
if (parents.length) {
taskName = parents.join(':') + ':' + taskName;
}
gulp.task(taskName, dependencies, func.bind(context));
}
function loadTasks(currentPath) {
var file = path.basename(currentPath);
var stats = fs.lstatSync(currentPath);
if (stats.isFile() && byExtension(file)) {
var pathWithoutBaseDir = currentPath.replace(path.normalize(opts.dir), '').substr(1);
var pathSegmentsCount = pathWithoutBaseDir.split(path.sep).length;
loadTask(pathWithoutBaseDir.split(path.sep).slice(0, pathSegmentsCount - 1), file);
}
else if (stats.isDirectory()) {
fs.readdirSync(currentPath)
.forEach(function(subPath){
loadTasks(path.join(currentPath, subPath));
});
}
}
loadTasks(opts.dir);
};