Normalize context for plugins

This commit is contained in:
Samy Pessé
2016-02-22 13:54:52 +01:00
parent 395bd62663
commit 71144db09c
3 changed files with 40 additions and 7 deletions
+24
View File
@@ -0,0 +1,24 @@
var error = require('../utils/error');
/*
Return the context for a plugin.
It tries to keep compatibilities with GitBook v2
*/
function pluginCtx(plugin) {
var book = plugin.book;
var ctx = {
config: book.config,
log: plugin.log,
// Paths
resolve: book.resolve
};
// Deprecation
error.deprecateField(ctx, 'options', book.config.dump(), '"options" property is deprecated, use config.get(key) instead');
return ctx;
}
module.exports = pluginCtx;
+10 -6
View File
@@ -10,6 +10,7 @@ var Promise = require('../utils/promise');
var error = require('../utils/error');
var gitbook = require('../gitbook');
var registry = require('./registry');
var pluginCtx = require('./context');
var HOOKS = [
'init', 'finish', 'finish:before', 'config', 'page', 'page:before'
@@ -25,7 +26,7 @@ function isModuleNotFound(err) {
function BookPlugin(book, pluginId) {
this.book = book;
this.log = this.book.log;
this.log = this.book.log.prefix(pluginId);
this.id = pluginId;
this.npmId = registry.npmId(pluginId);
@@ -45,6 +46,11 @@ BookPlugin.prototype.isLoaded = function() {
return Boolean(this.packageInfos && this.content);
};
// Bind a function to the plugin's context
BookPlugin.prototype.bind = function(fn) {
return fn.bind(pluginCtx(this));
};
// Load this plugin
// An optional folder to search in can be passed
BookPlugin.prototype.load = function(folder) {
@@ -173,9 +179,7 @@ BookPlugin.prototype.getConfigKey = function() {
// Call a hook and returns its result
BookPlugin.prototype.hook = function(name, input) {
// Our book will be the context to apply
var context = this.book;
var that = this;
var hookFunc = this.content.hooks? this.content.hooks[name] : null;
input = input || {};
@@ -188,7 +192,7 @@ BookPlugin.prototype.hook = function(name, input) {
return Promise()
.then(function() {
return hookFunc.apply(context, [input]);
return that.bind(hookFunc)(input);
});
};
@@ -214,7 +218,7 @@ BookPlugin.prototype._getResources = function(base) {
// Dynamic function
if(typeof book === 'function') {
// Call giving it the context of our book
return book.call(that.book);
return that.bind(book)();
}
// Plain data object
+6 -1
View File
@@ -17,7 +17,7 @@ var COLORS = {
ERROR: color.red
};
function Logger(write, logLevel) {
function Logger(write, logLevel, prefix) {
if (!(this instanceof Logger)) return new Logger(write, logLevel);
this._write = write || function(msg) { process.stdout.write(msg); };
@@ -40,6 +40,11 @@ function Logger(write, logLevel) {
}, this);
}
// Create a new logger prefixed from this logger
Logger.prototype.prefix = function(prefix) {
return (new Logger(this._write, this.logLevel, prefix));
};
// Change minimum level
Logger.prototype.setLevel = function(logLevel) {
if (_.isString(logLevel)) logLevel = LEVELS[logLevel.toUpperCase()];