diff options
author | Samy Pessé <samypesse@gmail.com> | 2015-10-13 13:56:46 +0200 |
---|---|---|
committer | Samy Pessé <samypesse@gmail.com> | 2015-10-13 13:56:46 +0200 |
commit | df5d27ab6103389294795a7fada76d46f36fc00f (patch) | |
tree | b5ce91ae52573db8574a5aa7a2bb9780a7c4d0a0 /lib/plugin.js | |
parent | 2870155c0b3b91efc2a4d3fe2e1edd5a1be9ae8a (diff) | |
download | gitbook-df5d27ab6103389294795a7fada76d46f36fc00f.zip gitbook-df5d27ab6103389294795a7fada76d46f36fc00f.tar.gz gitbook-df5d27ab6103389294795a7fada76d46f36fc00f.tar.bz2 |
Use jsonschema to valid and default plugins config
Diffstat (limited to 'lib/plugin.js')
-rw-r--r-- | lib/plugin.js | 29 |
1 files changed, 27 insertions, 2 deletions
diff --git a/lib/plugin.js b/lib/plugin.js index 3191c63..45d77b8 100644 --- a/lib/plugin.js +++ b/lib/plugin.js @@ -5,6 +5,8 @@ var path = require('path'); var url = require('url'); var fs = require('./utils/fs'); var resolve = require('resolve'); +var jsonschema = require('jsonschema'); +var jsonSchemaDefaults = require('json-schema-defaults'); var pkg = require('../package.json'); @@ -20,7 +22,7 @@ var Plugin = function(book, name) { _.each([ 'gitbook-plugin-'+name, 'gitbook-'+name, - name, + name ], function(_name) { // Load from the book if (this.load(_name, book.root)) return false; @@ -44,7 +46,7 @@ Plugin.prototype.load = function(name, baseDir) { this.baseDir = path.dirname(res); this.packageInfos = require(res); this.infos = require(resolve.sync(name, { basedir: baseDir })); - this.name = name; + this.name = this.packageInfos.name; return true; } catch (e) { @@ -139,6 +141,29 @@ Plugin.prototype.isValid = function() { return isValid; }; +// Normalize, validate configuration for this plugin using its schema +// Throw an error when shcema is not respected +Plugin.prototype.validateConfig = function(config) { + var that = this; + + return Q() + .then(function() { + var schema = that.packageInfos.gitbook || {}; + if (!schema) return config; + + // Normalize schema + schema.type = 'object'; + + // Validate and throw if invalid + var v = new jsonschema.Validator(); + v.validate(config, schema); + + // Insert default values + var defaults = jsonSchemaDefaults(schema); + return _.merge(defaults, config); + }); +}; + // Resolve file path Plugin.prototype.resolveFile = function(filename) { return path.resolve(this.baseDir, filename); |