Skip to content

Commit

Permalink
Merge pull request #134 from TheDancingCode/es2015
Browse files Browse the repository at this point in the history
Drop Node < 4 and refactor with ES2015 features
  • Loading branch information
jameelmoses committed Jun 28, 2019
2 parents a8f5b64 + 707912b commit 3a40353
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 76 deletions.
98 changes: 47 additions & 51 deletions index.js
@@ -1,19 +1,17 @@
'use strict';
var hasGulplog = require('has-gulplog');
var micromatch = require('micromatch');
var unique = require('array-unique');
var findup = require('findup-sync');
var resolve = require('resolve');
var path = require('path');
const hasGulplog = require('has-gulplog');
const micromatch = require('micromatch');
const unique = require('array-unique');
const findup = require('findup-sync');
const resolve = require('resolve');
const path = require('path');

function arrayify(el) {
return Array.isArray(el) ? el : [el];
}

function camelize(str) {
return str.replace(/-(\w)/g, function(m, p1) {
return p1.toUpperCase();
});
return str.replace(/-(\w)/g, (m, p1) => p1.toUpperCase());
}

// code from https://github.com/gulpjs/gulp-util/blob/master/lib/log.js
Expand All @@ -22,56 +20,56 @@ function camelize(str) {
function logger() {
if (hasGulplog()) {
// specifically deferring loading here to keep from registering it globally
var gulplog = require('gulplog');
const gulplog = require('gulplog');
gulplog.info.apply(gulplog, arguments);
} else {
// specifically defering loading because it might not be used
var fancylog = require('fancy-log');
const fancylog = require('fancy-log');
fancylog.apply(null, arguments);
}
}

function getPattern(options) {
var defaultPatterns = ['gulp-*', 'gulp.*', '@*/gulp{-,.}*'];
var overridePattern = 'overridePattern' in options ? !!options.overridePattern : true;
const defaultPatterns = ['gulp-*', 'gulp.*', '@*/gulp{-,.}*'];
const overridePattern = 'overridePattern' in options ? !!options.overridePattern : true;
if (overridePattern) {
return arrayify(options.pattern || defaultPatterns);
}
return defaultPatterns.concat(arrayify(options.pattern));
}

module.exports = function(options) {
var finalObject = {};
var configObject;
var requireFn;
const finalObject = {};
let configObject;
let requireFn;
options = options || {};

var DEBUG = options.DEBUG || false;
var pattern = getPattern(options);
var config = options.config || findup('package.json', { cwd: parentDir });
var scope = arrayify(options.scope || ['dependencies', 'devDependencies', 'peerDependencies']);
var replaceString = options.replaceString || /^gulp(-|\.)/;
var camelizePluginName = options.camelize !== false;
var lazy = 'lazy' in options ? !!options.lazy : true;
var renameObj = options.rename || {};
var maintainScope = 'maintainScope' in options ? !!options.maintainScope : true;
const DEBUG = options.DEBUG || false;
const pattern = getPattern(options);
const config = options.config || findup('package.json', { cwd: parentDir });
const scope = arrayify(options.scope || ['dependencies', 'devDependencies', 'peerDependencies']);
const replaceString = options.replaceString || /^gulp(-|\.)/;
const camelizePluginName = options.camelize !== false;
const lazy = 'lazy' in options ? !!options.lazy : true;
const renameObj = options.rename || {};
const maintainScope = 'maintainScope' in options ? !!options.maintainScope : true;

logDebug('Debug enabled with options: ' + JSON.stringify(options));
logDebug(`Debug enabled with options: ${JSON.stringify(options)}`);

var renameFn = options.renameFn || function(name) {
const renameFn = options.renameFn || function(name) {
name = name.replace(replaceString, '');
return camelizePluginName ? camelize(name) : name;
};

var postRequireTransforms = options.postRequireTransforms || {};
const postRequireTransforms = options.postRequireTransforms || {};

if (typeof options.requireFn === 'function') {
requireFn = options.requireFn;
} else if (typeof config === 'string') {
requireFn = function(name) {
// This searches up from the specified package.json file, making sure
// the config option behaves as expected. See issue #56.
var src = resolve.sync(name, { basedir: path.dirname(config) });
const src = resolve.sync(name, { basedir: path.dirname(config) });
return require(src);
};
} else {
Expand All @@ -84,76 +82,74 @@ module.exports = function(options) {
throw new Error('Could not find dependencies. Do you have a package.json file in your project?');
}

var names = scope.reduce(function(result, prop) {
return result.concat(Object.keys(configObject[prop] || {}));
}, []);
const names = scope.reduce((result, prop) => result.concat(Object.keys(configObject[prop] || {})), []);

logDebug(names.length + ' plugin(s) found: ' + names.join(' '));
logDebug(`${names.length} plugin(s) found: ${names.join(' ')}`);

pattern.push('!gulp-load-plugins');

function logDebug(message) {
if (DEBUG) {
logger('gulp-load-plugins: ' + message);
logger(`gulp-load-plugins: ${message}`);
}
}

function defineProperty(object, transform, requireName, name, maintainScope) {
var err;
let err;
if (object[requireName]) {
logDebug('error: defineProperty ' + name);
logDebug(`error: defineProperty ${name}`);
err = maintainScope
? 'Could not define the property "' + requireName + '", you may have repeated dependencies in your package.json like' + ' "gulp-' + requireName + '" and ' + '"' + requireName + '"'
: 'Could not define the property "' + requireName + '", you may have repeated a dependency in another scope like' + ' "gulp-' + requireName + '" and ' + '"@foo/gulp-' + requireName + '"';
? `Could not define the property "${requireName}", you may have repeated dependencies in your package.json like` + ` "gulp-${requireName}" and ` + `"${requireName}"`
: `Could not define the property "${requireName}", you may have repeated a dependency in another scope like` + ` "gulp-${requireName}" and ` + `"@foo/gulp-${requireName}"`;
throw new Error(err);
}

if (lazy) {
logDebug('lazyload: adding property ' + requireName);
logDebug(`lazyload: adding property ${requireName}`);
Object.defineProperty(object, requireName, {
enumerable: true,
get: function() {
logDebug('lazyload: requiring ' + name + '...');
logDebug(`lazyload: requiring ${name}...`);
return transform(requireName, requireFn(name));
}
});
} else {
logDebug('requiring ' + name + '...');
logDebug(`requiring ${name}...`);
object[requireName] = transform(requireName, requireFn(name));
}
}

function getRequireName(name) {
var requireName;
let requireName;

if (renameObj[name]) {
requireName = options.rename[name];
} else {
requireName = renameFn(name);
}

logDebug('renaming ' + name + ' to ' + requireName);
logDebug(`renaming ${name} to ${requireName}`);

return requireName;
}

function applyTransform(requireName, plugin) {
var transform = postRequireTransforms[requireName];
const transform = postRequireTransforms[requireName];

if (transform && typeof transform === 'function') { // if postRequireTransform function is passed, pass it the plugin and return it
logDebug('transforming ' + requireName);
logDebug(`transforming ${requireName}`);
return transform(plugin);
} else {
return plugin; // if no postRequireTransform function passed, return the plugin as is
}
}

var scopeTest = new RegExp('^@');
var scopeDecomposition = new RegExp('^@(.+)/(.+)');
const scopeTest = new RegExp('^@');
const scopeDecomposition = new RegExp('^@(.+)/(.+)');

unique(micromatch(names, pattern)).forEach(function(name) {
var decomposition;
var fObject = finalObject;
unique(micromatch(names, pattern)).forEach((name) => {
let decomposition;
let fObject = finalObject;
if (scopeTest.test(name)) {
decomposition = scopeDecomposition.exec(name);
if (maintainScope) {
Expand All @@ -172,7 +168,7 @@ module.exports = function(options) {
return finalObject;
};

var parentDir = path.dirname(module.parent.filename);
const parentDir = path.dirname(module.parent.filename);

// Necessary to get the current `module.parent` and resolve paths correctly.
delete require.cache[__filename];
3 changes: 3 additions & 0 deletions package.json
Expand Up @@ -10,6 +10,9 @@
"files": [
"index.js"
],
"engines": {
"node": ">=4"
},
"repository": "jackfranklin/gulp-load-plugins",
"keywords": [
"gulpfriendly",
Expand Down
50 changes: 25 additions & 25 deletions test/index.js
@@ -1,17 +1,17 @@
'use strict';
var assert = require('assert');
var sinon = require('sinon');
var capture = require('capture-stream');
var path = require('path');
const assert = require('assert');
const sinon = require('sinon');
const capture = require('capture-stream');
const path = require('path');

var gulpLoadPlugins = (function() {
var wrapInFunc = function(value) {
const gulpLoadPlugins = (function() {
const wrapInFunc = function(value) {
return function() {
return value;
};
};

var proxyquire = require('proxyquire').noCallThru();
const proxyquire = require('proxyquire').noCallThru();

return proxyquire('../', {
'gulp-foo': wrapInFunc({ name: 'foo' }),
Expand Down Expand Up @@ -71,9 +71,9 @@ describe('configuration', function() {
});

// Contains common tests with and without lazy mode.
var commonTests = function(lazy) {
const commonTests = function(lazy) {
it('loads things in', function() {
var x = gulpLoadPlugins({
const x = gulpLoadPlugins({
lazy: lazy,
config: {
dependencies: {
Expand Down Expand Up @@ -103,7 +103,7 @@ var commonTests = function(lazy) {
});

it('can take a pattern override', function() {
var x = gulpLoadPlugins({
const x = gulpLoadPlugins({
lazy: lazy,
pattern: 'jack-*',
replaceString: 'jack-',
Expand All @@ -122,7 +122,7 @@ var commonTests = function(lazy) {
});

it('can extend the patterns', function() {
var x = gulpLoadPlugins({
const x = gulpLoadPlugins({
lazy: lazy,
config: {
dependencies: {
Expand All @@ -141,7 +141,7 @@ var commonTests = function(lazy) {
});

it('allows camelizing to be turned off', function() {
var x = gulpLoadPlugins({
const x = gulpLoadPlugins({
lazy: lazy,
camelize: false,
config: {
Expand All @@ -157,7 +157,7 @@ var commonTests = function(lazy) {
});

it('camelizes plugins name by default', function() {
var x = gulpLoadPlugins({
const x = gulpLoadPlugins({
lazy: lazy,
config: {
dependencies: {
Expand All @@ -172,7 +172,7 @@ var commonTests = function(lazy) {
});

it('lets something be completely renamed', function() {
var x = gulpLoadPlugins({
const x = gulpLoadPlugins({
lazy: lazy,
config: { dependencies: { 'gulp-foo': '1.0.0' } },
rename: { 'gulp-foo': 'bar' }
Expand All @@ -182,9 +182,9 @@ var commonTests = function(lazy) {
});

it('outputs debug statements', function() {
var restore = capture(process.stdout);
const restore = capture(process.stdout);
try {
var x = gulpLoadPlugins({
const x = gulpLoadPlugins({
lazy: lazy,
DEBUG: true,
config: { dependencies: { 'gulp-foo': '*' } }
Expand All @@ -198,12 +198,12 @@ var commonTests = function(lazy) {
throw err;
}

var output = restore('true');
const output = restore('true');
assert(output.indexOf('gulp-load-plugins') !== -1, 'Expected output to be logged to stdout');
});

it('supports loading scopped package as a nested reference', function() {
var x = gulpLoadPlugins({
const x = gulpLoadPlugins({
lazy: lazy,
config: { dependencies: { '@myco/gulp-test-plugin': '1.0.0' } }
});
Expand All @@ -212,7 +212,7 @@ var commonTests = function(lazy) {
});

it('supports loading scopped package as a top-level reference', function() {
var x = gulpLoadPlugins({
const x = gulpLoadPlugins({
lazy: lazy,
maintainScope: false,
config: { dependencies: { '@myco/gulp-test-plugin': '1.0.0' } }
Expand All @@ -222,7 +222,7 @@ var commonTests = function(lazy) {
});

it('supports custom rename functions', function () {
var x = gulpLoadPlugins({
const x = gulpLoadPlugins({
renameFn: function () {
return 'baz';
},
Expand All @@ -243,7 +243,7 @@ var commonTests = function(lazy) {
});

it('supports transforming', function() {
var x = gulpLoadPlugins({
const x = gulpLoadPlugins({
lazy: lazy,
config: { dependencies: { 'gulp-foo': '1.0.0' } },
postRequireTransforms: {
Expand All @@ -261,7 +261,7 @@ var commonTests = function(lazy) {
describe('no lazy loading', function() {
commonTests(false);

var spy;
let spy;
before(function() {
spy = sinon.spy();
gulpLoadPlugins({
Expand All @@ -286,7 +286,7 @@ describe('no lazy loading', function() {
describe('with lazy loading', function() {
commonTests(true);

var x, spy;
let x, spy;
before(function() {
spy = sinon.spy();
x = gulpLoadPlugins({
Expand Down Expand Up @@ -315,15 +315,15 @@ describe('with lazy loading', function() {

describe('common functionality', function () {
it('throws a sensible error when not found', function () {
var x = gulpLoadPlugins({ config: path.join(__dirname, '/package.json') });
const x = gulpLoadPlugins({ config: path.join(__dirname, '/package.json') });

assert.throws(function () {
x.oops();
}, /Cannot find module 'gulp-oops'/);
});

it('allows you to use in a lower directory', function() {
var plugins = require('../')();
const plugins = require('../')();
assert.ok(typeof plugins.test === 'function');
});
});

0 comments on commit 3a40353

Please sign in to comment.