Improve performance of plugins listing

This commit is contained in:
Samy Pesse
2016-10-11 11:36:17 +02:00
parent 3a2abb870b
commit c71da9955e
+37 -52
View File
@@ -1,5 +1,4 @@
const readInstalled = require('read-installed');
const Immutable = require('immutable');
const { OrderedMap } = require('immutable');
const path = require('path');
const Promise = require('../utils/promise');
@@ -16,75 +15,61 @@ function validateId(name) {
return name && name.indexOf(PREFIX) === 0;
}
/**
* Read details about a node module.
* @param {String} modulePath
* @param {Number} depth
* @param {String} parent
* @return {Plugin} plugin
*/
function readModule(modulePath, depth, parent) {
const pkg = require(path.join(modulePath, 'package.json'));
const pluginName = pkg.name.slice(PREFIX.length);
return new Plugin({
name: pluginName,
version: pkg.version,
path: modulePath,
depth,
parent
});
}
/**
* List all packages installed inside a folder
*
* @param {String} folder
* @param {Number} depth
* @param {String} parent
* @return {OrderedMap<String:Plugin>}
*/
function findInstalled(folder) {
const options = {
dev: false,
log() {},
depth: 4
};
let results = Immutable.OrderedMap();
function onPackage(pkg, parent) {
if (!pkg.name) return;
const name = pkg.name;
const version = pkg.version;
const pkgPath = pkg.realPath;
const depth = pkg.depth;
const dependencies = pkg.dependencies;
const pluginName = name.slice(PREFIX.length);
if (!validateId(name)) {
if (parent) return;
} else {
results = results.set(pluginName, new Plugin({
name: pluginName,
version,
path: pkgPath,
depth,
parent
}));
}
Immutable.Map(dependencies).forEach(function(dep) {
onPackage(dep, pluginName);
});
}
function findInstalled(folder, depth = 0, parent = null) {
// Search for gitbook-plugins in node_modules folder
const node_modules = path.join(folder, 'node_modules');
// List all folders in node_modules
return fs.readdir(node_modules)
.fail(function() {
.fail(() => {
return Promise([]);
})
.then(function(modules) {
return Promise.serie(modules, function(module) {
.then((modules) => {
return Promise.reduce(modules, (results, moduleName) => {
// Not a gitbook-plugin
if (!validateId(module)) {
return Promise();
if (!validateId(moduleName)) {
return results;
}
// Read gitbook-plugin package details
const module_folder = path.join(node_modules, module);
return Promise.nfcall(readInstalled, module_folder, options)
.then(function(data) {
onPackage(data);
const moduleFolder = path.join(node_modules, moduleName);
const plugin = readModule(moduleFolder, depth, parent);
results = results.set(plugin.getName(), plugin);
return findInstalled(moduleFolder, depth + 1, plugin.getName())
.then((innerModules) => {
return results.merge(innerModules);
});
});
})
.then(function() {
// Return installed plugins
return results;
}, OrderedMap());
});
}