Last active
January 20, 2016 10:39
-
-
Save fxck/595149be34999dd59069 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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'] | |
}; | |
} | |
module.exports = function(options) { | |
if (isString(options)) { | |
options = { dir: 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 filterFiles(arg) { | |
if (!opts.filter) { | |
return true; | |
} else { | |
return arg.indexOf(opts.filter); | |
} | |
} | |
function loadTask(parent, task) { | |
var modulePath = path.join(process.cwd(), opts.dir, parent || '', 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 (parent) { | |
taskName = parent + ':' + taskName; | |
} | |
gulp.task(taskName, dependencies, func.bind(context)); | |
} | |
function resolvePath(dir) { | |
return path.join(opts.dir, dir); | |
} | |
function loadTasks(currentPath) { | |
var file = path.basename(currentPath); | |
var stats = fs.lstatSync(currentPath); | |
if (stats.isFile() && byExtension(file)) { | |
loadTask(null, file); | |
} | |
if (stats.isDirectory()) { | |
fs.readdirSync(currentPath) | |
.filter(byExtension) | |
.forEach(loadTask.bind(null, file)); | |
} | |
} | |
fs.readdirSync(opts.dir) | |
.filter(filterFiles) | |
.map(resolvePath) | |
.forEach(loadTasks); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment