diff options
author | Samy Pessé <samypesse@gmail.com> | 2015-09-15 14:21:27 +0200 |
---|---|---|
committer | Samy Pessé <samypesse@gmail.com> | 2015-09-15 14:21:27 +0200 |
commit | 6732957e42350b3aefa4b1c80371baea92950651 (patch) | |
tree | 1605473bf22c7e4ab90a6cc9bebf5cb807fa1d90 | |
parent | 5f56098ae7fae80a4dd75a944c38201560b480c6 (diff) | |
parent | 1fd00068595dfced5a0f16ac05ae2553d09608bc (diff) | |
download | gitbook-6732957e42350b3aefa4b1c80371baea92950651.zip gitbook-6732957e42350b3aefa4b1c80371baea92950651.tar.gz gitbook-6732957e42350b3aefa4b1c80371baea92950651.tar.bz2 |
Merge pull request #930 from GitbookIO/jshint
Add config for jshint and fix lint errors
47 files changed, 588 insertions, 613 deletions
diff --git a/.jshintrc b/.jshintrc new file mode 100644 index 0000000..748ef99 --- /dev/null +++ b/.jshintrc @@ -0,0 +1,7 @@ +{ + "strict": false, + "browser": false, + "quotmark": true, + "node": true, + "mocha": true +}
\ No newline at end of file diff --git a/lib/book.js b/lib/book.js index 08dd6dc..a7d0cd5 100644 --- a/lib/book.js +++ b/lib/book.js @@ -1,31 +1,25 @@ var Q = require("q"); var _ = require("lodash"); var path = require("path"); -var util = require("util"); var lunr = require("lunr"); var parsers = require("gitbook-parsers"); -var color = require("bash-color"); var fs = require("./utils/fs"); var parseNavigation = require("./utils/navigation"); var parseProgress = require("./utils/progress"); var pageUtil = require("./utils/page"); var pathUtil = require("./utils/path"); -var batch = require("./utils/batch"); var links = require("./utils/links"); var i18n = require("./utils/i18n"); var logger = require("./utils/logger"); var Configuration = require("./configuration"); var TemplateEngine = require("./template"); -var Plugin = require("./plugin"); var PluginsList = require("./pluginslist"); var generators = require("./generators"); var Book = function(root, context, parent) { - var that = this; - this.context = _.defaults(context || {}, { // Extend book configuration config: {}, @@ -86,10 +80,10 @@ var Book = function(root, context, parent) { // Search Index this.searchIndex = lunr(function () { - this.ref('url'); + this.ref("url"); - this.field('title', { boost: 10 }); - this.field('body'); + this.field("title", { boost: 10 }); + this.field("body"); }); // Bind methods @@ -125,12 +119,12 @@ Book.prototype.parse = function() { path.join(that.root, lang.path), _.merge({}, that.context, { config: _.extend({}, that.options, { - 'output': path.join(that.options.output, lang.lang), - 'language': lang.lang + "output": path.join(that.options.output, lang.lang), + "language": lang.lang }) }), that - ) + ); }); }); }) @@ -187,7 +181,7 @@ Book.prototype.generate = function(generator) { // Create generator .then(function() { var Generator = generators[generator]; - if (!Generator) throw "Generator '"+that.options.generator+"' doesn't exist"; + if (!Generator) throw "Generator \""+that.options.generator+"\" doesn't exist"; generator = new Generator(that); return generator.prepare(); @@ -212,9 +206,9 @@ Book.prototype.generate = function(generator) { return Q() - // First, let's create folder + // First, let"s create folder .then(function() { - return _.reduce(ops["directories"] || [], function(prev, folder) { + return _.reduce(ops.directories || [], function(prev, folder) { return prev.then(function() { that.log.debug.ln("transferring folder", folder); return Q(generator.transferFolder(folder)); @@ -222,18 +216,18 @@ Book.prototype.generate = function(generator) { }, Q()); }) - // Then, let's copy other files + // Then, let"s copy other files .then(function() { - return Q.all(_.map(ops["files"] || [], function(file) { + return Q.all(_.map(ops.files || [], function(file) { that.log.debug.ln("transferring file", file); return Q(generator.transferFile(file)); })); }) - // Finally let's generate content + // Finally let"s generate content .then(function() { - var nFiles = (ops["content"] || []).length; - return _.reduce(ops["content"] || [], function(prev, file, i) { + var nFiles = (ops.content || []).length; + return _.reduce(ops.content || [], function(prev, file, i) { return prev.then(function() { var p = ((i*100)/nFiles).toFixed(0)+"%"; that.log.debug.ln("processing", file, p); @@ -267,7 +261,7 @@ Book.prototype.generate = function(generator) { }; // Generate the output for a multilingual book -Book.prototype.generateMultiLingual = function(generator) { +Book.prototype.generateMultiLingual = function() { var that = this; return Q() @@ -295,7 +289,7 @@ Book.prototype.generateFile = function(output, options) { book.setOutput(tmpDir); return book.generate(options.ebookFormat) - .then(function(_options) { + .then(function() { var copyFile = function(lang) { var _outputFile = output; var _tmpDir = tmpDir; @@ -339,7 +333,7 @@ Book.prototype.generateFile = function(output, options) { Book.prototype.parseConfig = function() { var that = this; - that.log.info("loading book configuration....") + that.log.info("loading book configuration...."); return that.config.load() .then(function() { that.log.info.ok(); @@ -349,12 +343,11 @@ Book.prototype.parseConfig = function() { // Parse list of plugins Book.prototype.parsePlugins = function() { var that = this; - var failed = []; // Load plugins return that.plugins.load(that.options.plugins) .then(function() { - if (_.size(that.plugins.failed) > 0) return Q.reject(new Error("Error loading plugins: "+that.plugins.failed.join(",")+". Run 'gitbook install' to install plugins from NPM.")); + if (_.size(that.plugins.failed) > 0) return Q.reject(new Error("Error loading plugins: "+that.plugins.failed.join(",")+". Run \"gitbook install\" to install plugins from NPM.")); that.log.info.ok(that.plugins.count()+" plugins loaded"); that.log.debug.ln("normalize plugins list"); @@ -446,7 +439,7 @@ Book.prototype.parseSummary = function() { .then(function(content) { return summary.parser.summary(content, { entryPoint: that.readmeFile, - entryPointTitle: that.i18n('SUMMARY_INTRODUCTION'), + entryPointTitle: that.i18n("SUMMARY_INTRODUCTION"), files: that.files }) .fail(function(err) { @@ -575,7 +568,7 @@ Book.prototype.parsePage = function(filename, options) { .then(function(content) { section.content = content; return _sections.concat([section]); - }) + }); }); }, Q([])); }) @@ -587,8 +580,8 @@ Book.prototype.parsePage = function(filename, options) { convertImages: options.convertImages, input: filename, navigation: that.navigation, - base: path.dirname(filename) || './', - output: path.dirname(filename) || './', + base: path.dirname(filename) || "./", + output: path.dirname(filename) || "./", glossary: that.glossary }); }) @@ -623,7 +616,7 @@ Book.prototype.findFile = function(filename) { parser: parsers.get(ext), path: filepath }; - }) + }); }); }, Q(null)); }; @@ -658,28 +651,28 @@ Book.prototype.listAllFiles = function() { var that = this; return fs.list(this.root, { - ignoreFiles: ['.ignore', '.gitignore', '.bookignore'], + ignoreFiles: [".ignore", ".gitignore", ".bookignore"], ignoreRules: [ // Skip Git stuff - '.git/', - '.gitignore', + ".git/", + ".gitignore", // Skip OS X meta data - '.DS_Store', + ".DS_Store", // Skip stuff installed by plugins - 'node_modules', + "node_modules", // Skip book outputs - '_book', - '*.pdf', - '*.epub', - '*.mobi', + "_book", + "*.pdf", + "*.epub", + "*.mobi", // Skip config files - '.ignore', - '.bookignore', - 'book.json', + ".ignore", + ".bookignore", + "book.json", ] }) .then(function(_files) { @@ -688,7 +681,7 @@ Book.prototype.listAllFiles = function() { }; // Return true if the book is a multilingual book -Book.prototype.isMultilingual = function(filename) { +Book.prototype.isMultilingual = function() { return this.books.length > 0; }; @@ -698,7 +691,7 @@ Book.prototype.parentRoot = function() { return this.root; }; -// Return true if it's a sub-book +// Return true if it"s a sub-book Book.prototype.isSubBook = function() { return !!this.parent; }; @@ -727,20 +720,20 @@ Book.prototype.relative = function(p) { // Normalize a path to .html and convert README -> index Book.prototype.contentPath = function(link) { if ( - path.basename(link, path.extname(link)) == "README" - || link == this.readmeFile + path.basename(link, path.extname(link)) == "README" || + link == this.readmeFile ) { link = path.join(path.dirname(link), "index"+path.extname(link)); } link = links.changeExtension(link, ".html"); return link; -} +}; // Normalize a link to .html and convert README -> index Book.prototype.contentLink = function(link) { return links.normalize(this.contentPath(link)); -} +}; // Index a page into the search index Book.prototype.indexPage = function(page) { @@ -764,7 +757,7 @@ Book.prototype._defaultsStructure = function(filename) { that.summaryFile = that.summaryFile || that.config.getStructure("summary")+extension; that.glossaryFile = that.glossaryFile || that.config.getStructure("glossary")+extension; that.langsFile = that.langsFile || that.config.getStructure("langs")+extension; -} +}; // Change output path Book.prototype.setOutput = function(p) { @@ -777,7 +770,7 @@ Book.prototype.setOutput = function(p) { }; // Translate a strign according to the book language -Book.prototype.i18n = function(phrase) { +Book.prototype.i18n = function() { var args = Array.prototype.slice.call(arguments); return i18n.__.apply({}, [this.config.normalizeLanguage()].concat(args)); }; @@ -796,10 +789,10 @@ Book.prototype.normError = function(err, opts, defs) { err.toString = function() { var attributes = []; - if (this.fileName) attributes.push("In file '"+this.fileName+"'"); + if (this.fileName) attributes.push("In file \""+this.fileName+"\""); if (this.lineNumber) attributes.push("Line "+this.lineNumber); if (this.columnNumber) attributes.push("Column "+this.columnNumber); - return (this.name || "Error")+": "+this.message+((attributes.length > 0)? " ("+attributes.join(", ")+")" : "") + return (this.name || "Error")+": "+this.message+((attributes.length > 0)? " ("+attributes.join(", ")+")" : ""); }; return err; @@ -837,7 +830,7 @@ Book.init = function(root, opts) { var chapters = book.summary.chapters || []; extensionToUse = path.extname(summary); - if (chapters.length == 0) { + if (chapters.length === 0) { chapters = [ { title: "Summary", @@ -853,7 +846,7 @@ Book.init = function(root, opts) { return Q(chaptersPaths(chapters)); }) .then(function(chapters) { - // Create files that don't exist + // Create files that don"t exist return Q.all(_.map(chapters, function(chapter) { if (!chapter.path) return Q(); var absolutePath = path.resolve(book.root, chapter.path); @@ -869,7 +862,7 @@ Book.init = function(root, opts) { return fs.mkdirp(path.dirname(absolutePath)) .then(function() { - return fs.writeFile(absolutePath, '# '+chapter.title+'\n'); + return fs.writeFile(absolutePath, "# "+chapter.title+"\n"); }); }); })); diff --git a/lib/configuration.js b/lib/configuration.js index acff1c1..34d6351 100644 --- a/lib/configuration.js +++ b/lib/configuration.js @@ -1,14 +1,13 @@ var _ = require("lodash"); var Q = require("q"); var path = require("path"); -var semver = require('semver'); +var semver = require("semver"); -var pkg = require('../package.json'); -var fs = require("./utils/fs"); +var pkg = require("../package.json"); var i18n = require("./utils/i18n"); // Default plugins added to each books -var defaultsPlugins = ['highlight']; +var defaultsPlugins = ["highlight"]; // Normalize a list of plugins to use function normalizePluginsList(plugins) { @@ -24,9 +23,9 @@ function normalizePluginsList(plugins) { var parts = plugin.split("@"); return { - 'name': parts[0], - 'version': parts[1] // optional - } + "name": parts[0], + "version": parts[1] // optional + }; }); // List plugins to remove @@ -42,7 +41,7 @@ function normalizePluginsList(plugins) { // Merge with defaults plugins = _.chain(plugins) .concat(_.map(defaultsPlugins, function(plugin) { - return { 'name': plugin } + return { "name": plugin }; })) .uniq() .value(); @@ -55,11 +54,6 @@ function normalizePluginsList(plugins) { return plugins; } -// Normalize a list of plugin name to use -function normalizePluginsNames(plugins) { - return _.pluck(normalizePluginsList(plugins), "name"); -}; - var Configuration = function(book, options) { var that = this; @@ -96,7 +90,7 @@ Configuration.prototype.load = function() { return Q() .then(function() { - var configPath, config; + var configPath, _config; try { configPath = require.resolve( @@ -109,7 +103,7 @@ Configuration.prototype.load = function() { _config = require(configPath); that.options = _.merge( that.options, - _.omit(_config, 'configFile', 'defaultsPlugins', 'generator', 'extension') + _.omit(_config, "configFile", "defaultsPlugins", "generator", "extension") ); } catch(err) { @@ -121,7 +115,7 @@ Configuration.prototype.load = function() { if (!semver.satisfies(pkg.version, that.options.gitbook)) { throw "GitBook version doesn't satisfy version required by the book: "+that.options.gitbook; } - if (that.options.gitbook != '*' && !semver.satisfies(semver.inc(pkg.version, 'patch'), that.options.gitbook)) { + if (that.options.gitbook != "*" && !semver.satisfies(semver.inc(pkg.version, "patch"), that.options.gitbook)) { that.book.log.warn.ln("gitbook version specified in your book.json might be too strict for future patches, \""+(_.first(pkg.version.split("."))+".x.x")+"\" is more adequate"); } @@ -163,7 +157,7 @@ Configuration.prototype.get = function(key, def) { // Default configuration Configuration.DEFAULT = { - // Options that can't be extend + // Options that can"t be extend "configFile": "book", "generator": "website", "extension": null, @@ -213,9 +207,9 @@ Configuration.DEFAULT = { "variables": {}, // Set another theme with your own layout - // It's recommended to use plugins or add more options for default theme, though + // It"s recommended to use plugins or add more options for default theme, though // See https://github.com/GitbookIO/gitbook/issues/209 - "theme": path.resolve(__dirname, '../theme'), + "theme": path.resolve(__dirname, "../theme"), // Links in template (null: default, false: remove, string: new value) "links": { diff --git a/lib/conrefs_loader.js b/lib/conrefs_loader.js index 72dce8a..a6c2049 100644 --- a/lib/conrefs_loader.js +++ b/lib/conrefs_loader.js @@ -1,4 +1,3 @@ -var Q = require("q"); var path = require("path"); var nunjucks = require("nunjucks"); @@ -29,7 +28,7 @@ var BookLoader = nunjucks.Loader.extend({ return { src: source.toString(), path: filepath - } + }; }); }) .nodeify(callback); diff --git a/lib/generator.js b/lib/generator.js index 407afa5..fca5b3c 100644 --- a/lib/generator.js +++ b/lib/generator.js @@ -3,8 +3,6 @@ var path = require("path"); var Q = require("q"); var fs = require("./utils/fs"); -var Plugin = require("./plugin"); - var BaseGenerator = function(book) { this.book = book; @@ -65,7 +63,7 @@ BaseGenerator.prototype.copyCover = function() { fs.copy(path.join(that.book.parentRoot(), "cover_small.jpg"), path.join(that.options.output, "cover_small.jpg")) ]); }) - .fail(function(err) { + .fail(function() { return Q(); }); }; diff --git a/lib/generators/ebook.js b/lib/generators/ebook.js index cdb667c..e6a33d3 100644 --- a/lib/generators/ebook.js +++ b/lib/generators/ebook.js @@ -2,7 +2,7 @@ var util = require("util"); var path = require("path"); var Q = require("q"); var _ = require("lodash"); -var exec = require('child_process').exec; +var exec = require("child_process").exec; var fs = require("../utils/fs"); var stringUtils = require("../utils/string"); @@ -26,9 +26,9 @@ var Generator = function(book, format) { util.inherits(Generator, BaseGenerator); Generator.prototype.prepareTemplates = function() { - this.templates["page"] = this.book.plugins.template("ebook:page") || path.resolve(this.options.theme, 'templates/ebook/page.html'); - this.templates["summary"] = this.book.plugins.template("ebook:summary") || path.resolve(this.options.theme, 'templates/ebook/summary.html'); - this.templates["glossary"] = this.book.plugins.template("ebook:glossary") || path.resolve(this.options.theme, 'templates/ebook/glossary.html'); + this.templates.page = this.book.plugins.template("ebook:page") || path.resolve(this.options.theme, "templates/ebook/page.html"); + this.templates.summary = this.book.plugins.template("ebook:summary") || path.resolve(this.options.theme, "templates/ebook/summary.html"); + this.templates.glossary = this.book.plugins.template("ebook:glossary") || path.resolve(this.options.theme, "templates/ebook/glossary.html"); return Q(); }; @@ -38,7 +38,7 @@ Generator.prototype.writeSummary = function() { var that = this; that.book.log.info.ln("write SUMMARY.html"); - return this._writeTemplate(this.templates["summary"], {}, path.join(this.options.output, "SUMMARY.html")); + return this._writeTemplate(this.templates.summary, {}, path.join(this.options.output, "SUMMARY.html")); }; Generator.prototype.finish = function() { @@ -52,12 +52,12 @@ Generator.prototype.finish = function() { .then(function() { if (!that.ebookFormat) return Q(); - var d = Q.defer(); - if (!that.options.cover && fs.existsSync(path.join(that.options.output, "cover.jpg"))) { that.options.cover = path.join(that.options.output, "cover.jpg"); } + var d = Q.defer(); + var _options = { "--cover": that.options.cover, "--title": that.options.title, @@ -108,7 +108,7 @@ Generator.prototype.finish = function() { that.book.log.info("start conversion to", that.ebookFormat, "...."); - var child = exec(command, function (error, stdout, stderr) { + var child = exec(command, function (error, stdout) { if (error) { that.book.log.info.fail(); @@ -124,11 +124,11 @@ Generator.prototype.finish = function() { d.resolve(); }); - child.stdout.on('data', function (data) { + child.stdout.on("data", function (data) { that.book.log.debug(data); }); - child.stderr.on('data', function (data) { + child.stderr.on("data", function (data) { that.book.log.debug(data); }); diff --git a/lib/generators/json.js b/lib/generators/json.js index 6c9439d..446ef0d 100644 --- a/lib/generators/json.js +++ b/lib/generators/json.js @@ -13,7 +13,7 @@ var Generator = function() { util.inherits(Generator, BaseGenerator); // Ignore some methods -Generator.prototype.transferFile = function(input) { }; +Generator.prototype.transferFile = function() { }; // Convert an input file Generator.prototype.convertFile = function(input) { @@ -44,7 +44,7 @@ Generator.prototype.finish = function() { // Write README.json Generator.prototype.writeReadme = function() { var that = this; - var mainlang, langs; + var mainLang, langs, readme; return Q() .then(function() { diff --git a/lib/generators/website.js b/lib/generators/website.js index 675092f..4bde473 100644 --- a/lib/generators/website.js +++ b/lib/generators/website.js @@ -10,7 +10,6 @@ var FilterExtension = require("nunjucks-filter")(nunjucks); var fs = require("../utils/fs"); var BaseGenerator = require("../generator"); var links = require("../utils/links"); -var pageUtil = require("../utils/page"); var i18n = require("../utils/i18n"); var pkg = require("../../package.json"); @@ -64,9 +63,9 @@ Generator.prototype.prepareStyles = function() { // Prepare templates Generator.prototype.prepareTemplates = function() { - this.templates["page"] = this.book.plugins.template("site:page") || path.resolve(this.options.theme, 'templates/website/page.html'); - this.templates["langs"] = this.book.plugins.template("site:langs") || path.resolve(this.options.theme, 'templates/website/langs.html'); - this.templates["glossary"] = this.book.plugins.template("site:glossary") || path.resolve(this.options.theme, 'templates/website/glossary.html'); + this.templates.page = this.book.plugins.template("site:page") || path.resolve(this.options.theme, "templates/website/page.html"); + this.templates.langs = this.book.plugins.template("site:langs") || path.resolve(this.options.theme, "templates/website/langs.html"); + this.templates.glossary = this.book.plugins.template("site:glossary") || path.resolve(this.options.theme, "templates/website/glossary.html"); return Q(); }; @@ -98,13 +97,13 @@ Generator.prototype.prepareTemplateEngine = function() { // Add filter that.env.addFilter("contentLink", that.book.contentLink.bind(that.book)); - that.env.addFilter('lvl', function(lvl) { + that.env.addFilter("lvl", function(lvl) { return lvl.split(".").length; }); // Add extension - that.env.addExtension('AutoEscapeExtension', new AutoEscapeExtension(that.env)); - that.env.addExtension('FilterExtension', new FilterExtension(that.env)); + that.env.addExtension("AutoEscapeExtension", new AutoEscapeExtension(that.env)); + that.env.addExtension("FilterExtension", new FilterExtension(that.env)); }); }; @@ -114,7 +113,7 @@ Generator.prototype.finish = function() { .then(this.copyCover) .then(this.writeGlossary) .then(this.writeSearchIndex) - .then(this.writeLangsIndex) + .then(this.writeLangsIndex); }; // Convert an input file @@ -135,11 +134,11 @@ Generator.prototype.convertFile = function(input) { var output = path.join(that.options.output, relativeOutput); var basePath = path.relative(path.dirname(output), that.options.output) || "."; - if (process.platform === 'win32') basePath = basePath.replace(/\\/g, '/'); + if (process.platform === "win32") basePath = basePath.replace(/\\/g, "/"); that.book.log.debug.ln("write parsed file", page.path, "to", relativeOutput); - return that._writeTemplate(that.templates["page"], { + return that._writeTemplate(that.templates.page, { progress: page.progress, _input: page.path, @@ -153,27 +152,23 @@ Generator.prototype.convertFile = function(input) { // Write the index for langs Generator.prototype.writeLangsIndex = function() { - var that = this; if (!this.book.langs.length) return Q(); - return this._writeTemplate(this.templates["langs"], { + + return this._writeTemplate(this.templates.langs, { langs: this.book.langs }, path.join(this.options.output, "index.html")); }; // Write glossary Generator.prototype.writeGlossary = function() { - var that = this; - // No glossary - if (this.book.glossary.length == 0) return Q(); + if (this.book.glossary.length === 0) return Q(); - return this._writeTemplate(this.templates["glossary"], {}, path.join(this.options.output, "GLOSSARY.html")); + return this._writeTemplate(this.templates.glossary, {}, path.join(this.options.output, "GLOSSARY.html")); }; // Write the search index Generator.prototype.writeSearchIndex = function() { - var that = this; - return fs.writeFile( path.join(this.options.output, "search_index.json"), JSON.stringify(this.book.searchIndex) @@ -207,7 +202,7 @@ Generator.prototype._writeTemplate = function(tpl, options, output, interpolate) interpolate = interpolate || _.identity; return Q() - .then(function(sections) { + .then(function() { return that.env.render( tpl, _.extend({ @@ -239,7 +234,7 @@ Generator.prototype._writeTemplate = function(tpl, options, output, interpolate) basePath: ".", staticBase: path.join(".", "gitbook"), - '__': that.book.i18n.bind(that.book) + "__": that.book.i18n.bind(that.book) }, options) ); }) diff --git a/lib/index.js b/lib/index.js index b5aa06d..89d5d3c 100644 --- a/lib/index.js +++ b/lib/index.js @@ -1,11 +1,10 @@ var Q = require("q"); var _ = require("lodash"); var path = require("path"); -var tinylr = require('tiny-lr'); -var color = require('bash-color'); +var tinylr = require("tiny-lr"); +var color = require("bash-color"); var Book = require("./book"); -var Plugin = require("./plugin"); var Server = require("./utils/server"); var stringUtils = require("./utils/string"); var watch = require("./utils/watch"); @@ -42,10 +41,10 @@ module.exports = { var output = args[1] || path.join(input, "_book"); var book = new Book(input, _.extend({}, { - 'config': { - 'output': output + "config": { + "output": output }, - 'logLevel': kwargs.log + "logLevel": kwargs.log })); return book.parse() @@ -71,7 +70,7 @@ module.exports = { var output = args[1]; var book = new Book(input, _.extend({}, { - 'logLevel': kwargs.log + "logLevel": kwargs.log })); return book.parse() @@ -116,7 +115,7 @@ module.exports = { // Init livereload server var lrServer = tinylr({}); - var lrPath = undefined; + var lrPath; var generate = function() { if (server.isRunning()) console.log("Stopping server"); @@ -124,10 +123,10 @@ module.exports = { return server.stop() .then(function() { var book = new Book(input, _.extend({}, { - 'config': { - 'defaultsPlugins': ["livereload"] + "config": { + "defaultsPlugins": ["livereload"] }, - 'logLevel': kwargs.log + "logLevel": kwargs.log })); return book.parse() @@ -138,10 +137,10 @@ module.exports = { }) .then(function(book) { console.log(); - console.log('Starting server ...'); + console.log("Starting server ..."); return server.start(book.options.output, kwargs.port) .then(function() { - console.log('Serving book on http://localhost:'+kwargs.port); + console.log("Serving book on http://localhost:"+kwargs.port); if (lrPath) { // trigger livereload @@ -159,18 +158,18 @@ module.exports = { // set livereload path lrPath = filepath; console.log("Restart after change in file", filepath); - console.log(''); + console.log(""); return generate(); - }) - }) + }); + }); }); }; return Q.nfcall(lrServer.listen.bind(lrServer), kwargs.lrport) .then(function() { - console.log('Live reload server started on port:', kwargs.lrport); - console.log('Press CTRL+C to quit ...'); - console.log('') + console.log("Live reload server started on port:", kwargs.lrport); + console.log("Press CTRL+C to quit ..."); + console.log(""); return generate(); }); } @@ -179,7 +178,7 @@ module.exports = { { name: "install [book]", description: "install plugins dependencies", - exec: function(args, kwargs) { + exec: function(args) { var input = args[0] || process.cwd(); var book = new Book(input); @@ -198,7 +197,7 @@ module.exports = { { name: "init [directory]", description: "create files and folders based on contents of SUMMARY.md", - exec: function(args, kwargs) { + exec: function(args) { return Book.init(args[0] || process.cwd()) .then(function(){ console.log(""); diff --git a/lib/plugin.js b/lib/plugin.js index 364aec8..5e1c427 100644 --- a/lib/plugin.js +++ b/lib/plugin.js @@ -4,7 +4,7 @@ var semver = require("semver"); var path = require("path"); var url = require("url"); var fs = require("./utils/fs"); -var resolve = require('resolve'); +var resolve = require("resolve"); var pkg = require("../package.json"); @@ -34,7 +34,7 @@ var Plugin = function(book, name) { Plugin.RESOURCES = ["js", "css"]; Plugin.HOOKS = [ "init", "finish", "finish:before", "page", "page:before" -] +]; // Load from a name Plugin.prototype.load = function(name, baseDir) { @@ -77,7 +77,7 @@ Plugin.prototype._getResources = function(base) { var book = this.infos[base]; // Compatibility with version 1.x.x - if (base == "website") book = book || this.infos["book"]; + if (base == "website") book = book || this.infos.book; // Nothing specified, fallback to default if (!book) { @@ -168,7 +168,7 @@ Plugin.prototype.copyAssets = function(out, base) { var that = this; return this.getResources(base) - .get('assets') + .get("assets") .then(function(assets) { // Assets are undefined if(!assets) return false; diff --git a/lib/pluginslist.js b/lib/pluginslist.js index 37dbd41..ec9f4c8 100644 --- a/lib/pluginslist.js +++ b/lib/pluginslist.js @@ -1,14 +1,14 @@ var _ = require("lodash"); var Q = require("q"); -var npmi = require('npmi'); -var npm = require('npm'); -var semver = require('semver'); +var npmi = require("npmi"); +var npm = require("npm"); +var semver = require("semver"); var Plugin = require("./plugin"); var pkg = require("../package.json"); var initNPM = _.memoize(function() { - return Q.nfcall(npm.load, { silent: true, loglevel: 'silent' }); + return Q.nfcall(npm.load, { silent: true, loglevel: "silent" }); }); @@ -53,7 +53,7 @@ PluginsList.prototype.count = function() { }; // Add and load a plugin -PluginsList.prototype.load = function(plugin, options) { +PluginsList.prototype.load = function(plugin) { var that = this; if (_.isArray(plugin)) { @@ -103,7 +103,7 @@ PluginsList.prototype.load = function(plugin, options) { namespace.html[tag] = namespace.html[tag] || []; namespace.html[tag].push(value); }); - }) + }); }); }, Q()); }; @@ -146,7 +146,7 @@ PluginsList.prototype.resources = function(namespace) { // Install plugins from a book PluginsList.prototype.install = function() { var that = this; - var defaultsPlugins = _.pluck(that.book.options.defaultsPlugins) + var defaultsPlugins = _.pluck(that.book.options.defaultsPlugins); // Remove defaults (no need to install) var plugins = _.filter(that.book.options.plugins, function(plugin) { @@ -176,8 +176,8 @@ PluginsList.prototype.install = function() { .map(function(v) { return { version: v[0], - gitbook: (v[1].engines || {})["gitbook"] - } + gitbook: (v[1].engines || {}).gitbook + }; }) .filter(function(v) { return v.gitbook && semver.satisfies(pkg.version, v.gitbook); @@ -199,13 +199,13 @@ PluginsList.prototype.install = function() { that.book.log.info.ln("install plugin", plugin.name, "from npm ("+fullname+") with version", version); return Q.nfcall(npmi, { - 'name': fullname, - 'version': version, - 'path': that.book.root, - 'npmLoad': { - 'loglevel': 'silent', - 'loaded': true, - 'prefix': that.book.root + "name": fullname, + "version": version, + "path": that.book.root, + "npmLoad": { + "loglevel": "silent", + "loaded": true, + "prefix": that.book.root } }); }) @@ -216,6 +216,4 @@ PluginsList.prototype.install = function() { }, Q()); }; - - module.exports = PluginsList; diff --git a/lib/template.js b/lib/template.js index 41362c8..d9d3a2f 100644 --- a/lib/template.js +++ b/lib/template.js @@ -1,13 +1,12 @@ var _ = require("lodash"); var Q = require("q"); -var path = require("path"); var nunjucks = require("nunjucks"); var escapeStringRegexp = require("escape-string-regexp"); var batch = require("./utils/batch"); var pkg = require("../package.json"); var defaultBlocks = require("./blocks"); -var BookLoader = require("./conrefs_loader") +var BookLoader = require("./conrefs_loader"); // Normalize result from a block function normBlockResult(blk) { @@ -29,12 +28,12 @@ var TemplateEngine = function(book) { // Tags tags: { - blockStart: '{%', - blockEnd: '%}', - variableStart: '{{', - variableEnd: '}}', - commentStart: '{###', - commentEnd: '###}' + blockStart: "{%", + blockEnd: "%}", + variableStart: "{{", + variableEnd: "}}", + commentStart: "{###", + commentEnd: "###}" } } ); @@ -63,7 +62,7 @@ TemplateEngine.prototype.processBlock = function(blk) { }); blk.id = _.uniqueId("blk"); - var toAdd = (!blk.parse) || (blk.post != undefined); + var toAdd = (!blk.parse) || (blk.post !== undefined); // Add to global map if (toAdd) this.blockBodies[blk.id] = blk; @@ -111,11 +110,11 @@ TemplateEngine.prototype.bindContext = function(func) { TemplateEngine.prototype.addFilter = function(filterName, func) { try { this.env.getFilter(filterName); - this.log.warn.ln("conflict in filters, '"+filterName+"' is already set"); + this.log.warn.ln("conflict in filters, \""+filterName+"\" is already set"); return false; } catch(e) {} - this.log.debug.ln("add filter '"+filterName+"'"); + this.log.debug.ln("add filter \""+filterName+"\""); this.env.addFilter(filterName, this.bindContext(function() { var ctx = this; var args = Array.prototype.slice.apply(arguments); @@ -139,7 +138,7 @@ TemplateEngine.prototype.addFilters = function(filters) { // Return nunjucks extension name of a block TemplateEngine.prototype.blockExtName = function(name) { - return 'Block'+name+'Extension'; + return "Block"+name+"Extension"; }; // Test if a block is defined @@ -173,22 +172,22 @@ TemplateEngine.prototype.addBlock = function(name, block) { blocks: [] }); - var extName = this.blockExtName(name); + extName = this.blockExtName(name); if (this.hasBlock(name) && !defaultBlocks[name]) { - this.log.warn.ln("conflict in blocks, '"+name+"' is already defined"); + this.log.warn.ln("conflict in blocks, \""+name+"\" is already defined"); } // Cleanup previous block this.removeBlock(name); - this.log.debug.ln("add block '"+name+"'"); + this.log.debug.ln("add block \""+name+"\""); this.blocks[name] = block; - var Ext = function () { + Ext = function () { this.tags = [name]; - this.parse = function(parser, nodes, lexer) { + this.parse = function(parser, nodes) { var body = null; var lastBlockName = null; var lastBlockArgs = null; @@ -229,7 +228,7 @@ TemplateEngine.prototype.addBlock = function(name, block) { var bodies = [body]; _.each(block.blocks, function(blockName) { subbodies[blockName] = subbodies[blockName] || []; - if (subbodies[blockName].length == 0) { + if (subbodies[blockName].length === 0) { subbodies[blockName].push({ args: new nodes.NodeList(), body: new nodes.NodeList() @@ -239,7 +238,7 @@ TemplateEngine.prototype.addBlock = function(name, block) { bodies.push(subbodies[blockName][0].body); }); - return new nodes.CallExtensionAsync(this, 'run', args, bodies); + return new nodes.CallExtensionAsync(this, "run", args, bodies); }; this.run = function(context) { @@ -273,12 +272,12 @@ TemplateEngine.prototype.addBlock = function(name, block) { args: args, kwargs: kwargs, blocks: _blocks - }); + }, context); }) // process the block returned .then(that.processBlock) - .nodeify(callback) + .nodeify(callback); }; }; @@ -288,7 +287,7 @@ TemplateEngine.prototype.addBlock = function(name, block) { // Add shortcuts if (!_.isArray(block.shortcuts)) block.shortcuts = [block.shortcuts]; _.each(block.shortcuts, function(shortcut) { - this.log.debug.ln("add template shortcut from '"+shortcut.start+"' to block '"+name+"' for parsers ", shortcut.parsers); + this.log.debug.ln("add template shortcut from \""+shortcut.start+"\" to block \""+name+"\" for parsers ", shortcut.parsers); this.shortcuts.push({ block: name, parsers: shortcut.parsers, @@ -311,11 +310,11 @@ TemplateEngine.prototype.addBlocks = function(blocks) { // Apply a block to some content // This method result depends on the type of block (async or sync) -TemplateEngine.prototype.applyBlock = function(name, blk) { - var func, block, func, r; +TemplateEngine.prototype.applyBlock = function(name, blk, ctx) { + var func, block, r; block = this.blocks[name]; - if (!block) throw new Error('Block not found "'+name+'"'); + if (!block) throw new Error("Block not found \""+name+"\""); if (_.isString(blk)) { blk = { body: blk @@ -330,7 +329,7 @@ TemplateEngine.prototype.applyBlock = function(name, blk) { // Bind and call block processor func = this.bindContext(block.process); - r = func(blk); + r = func.call(ctx || {}, blk); if (Q.isPromise(r)) return r.then(normBlockResult); else return normBlockResult(r); @@ -341,7 +340,7 @@ TemplateEngine.prototype._applyShortcut = function(parser, content, shortcut) { if (!_.contains(shortcut.parsers, parser)) return content; var regex = new RegExp( escapeStringRegexp(shortcut.start) + "([\\s\\S]*?[^\\$])" + escapeStringRegexp(shortcut.end), - 'g' + "g" ); return content.replace(regex, function(all, match) { return "{% "+shortcut.tag.start+" %}"+ match + "{% "+shortcut.tag.end+" %}"; @@ -350,7 +349,7 @@ TemplateEngine.prototype._applyShortcut = function(parser, content, shortcut) { // Render a string from the book TemplateEngine.prototype.renderString = function(content, context, options) { - var context = _.extend({}, context, { + context = _.extend({}, context, { // Variables from book.json book: this.book.options.variables, @@ -382,8 +381,8 @@ TemplateEngine.prototype.renderString = function(content, context, options) { }; // Render a file from the book -TemplateEngine.prototype.renderFile = function(filename, options) { - var that = this, context; +TemplateEngine.prototype.renderFile = function(filename) { + var that = this; return that.book.readFile(filename) .then(function(content) { @@ -395,7 +394,7 @@ TemplateEngine.prototype.renderFile = function(filename, options) { // Render a page from the book TemplateEngine.prototype.renderPage = function(page) { - var that = this, context; + var that = this; return that.book.statFile(page.path) .then(function(stat) { diff --git a/lib/utils/batch.js b/lib/utils/batch.js index bd3b80f..9069766 100644 --- a/lib/utils/batch.js +++ b/lib/utils/batch.js @@ -3,12 +3,12 @@ var _ = require("lodash"); // Execute a method for all element function execEach(items, options) { - if (_.size(items) == 0) return Q(); + if (_.size(items) === 0) return Q(); var concurrents = 0, d = Q.defer(), pending = []; options = _.defaults(options || {}, { max: 100, - fn: function(item) {} + fn: function() {} }); @@ -29,7 +29,7 @@ function execEach(items, options) { // Next pending var next = pending.shift(); - if (concurrents == 0 && !next) { + if (concurrents === 0 && !next) { d.resolve(); } else if (next) { startItem.apply(null, next); @@ -38,7 +38,7 @@ function execEach(items, options) { .fail(function(err) { pending = []; d.reject(err); - }) + }); } _.each(items, startItem); diff --git a/lib/utils/fs.js b/lib/utils/fs.js index 176a215..0a9d846 100644 --- a/lib/utils/fs.js +++ b/lib/utils/fs.js @@ -9,10 +9,10 @@ var Ignore = require("fstream-ignore"); var fsUtils = { tmp: { file: function(opt) { - return Q.nfcall(tmp.file.bind(tmp), opt).get(0) + return Q.nfcall(tmp.file.bind(tmp), opt).get(0); }, dir: function() { - return Q.nfcall(tmp.dir.bind(tmp)).get(0) + return Q.nfcall(tmp.dir.bind(tmp)).get(0); } }, list: listFiles, @@ -34,14 +34,14 @@ var fsUtils = { readFileSync: fs.readFileSync.bind(fs), clean: cleanFolder, getUniqueFilename: getUniqueFilename, -} +}; // Write a file function writeFile(filename, data, options) { var d = Q.defer(); try { - fs.writeFileSync(filename, data, options) + fs.writeFileSync(filename, data, options); } catch(err) { d.reject(err); } @@ -57,14 +57,14 @@ function writeStream(filename, st) { var wstream = fs.createWriteStream(filename); - wstream.on('finish', function () { + wstream.on("finish", function () { d.resolve(); }); - wstream.on('error', function (err) { + wstream.on("error", function (err) { d.reject(err); }); - st.on('error', function(err) { + st.on("error", function(err) { d.reject(err); }); @@ -115,20 +115,20 @@ function listFiles(root, options) { }); // Add extra rules to ignore common folders - ig.addIgnoreRules(options.ignoreRules, '__custom_stuff'); + ig.addIgnoreRules(options.ignoreRules, "__custom_stuff"); // Push each file to our list - ig.on('child', function (c) { + ig.on("child", function (c) { files.push( - c.path.substr(c.root.path.length + 1) + (c.props.Directory === true ? '/' : '') + c.path.substr(c.root.path.length + 1) + (c.props.Directory === true ? "/" : "") ); }); - ig.on('end', function() { + ig.on("end", function() { // Normalize paths on Windows - if(process.platform === 'win32') { + if(process.platform === "win32") { return d.resolve(files.map(function(file) { - return file.replace(/\\/g, '/'); + return file.replace(/\\/g, "/"); })); } @@ -136,7 +136,7 @@ function listFiles(root, options) { return d.resolve(files); }); - ig.on('error', d.reject); + ig.on("error", d.reject); return d.promise; } @@ -150,8 +150,8 @@ function cleanFolder(root) { ignoreFiles: [], ignoreRules: [ // Skip Git and SVN stuff - '.git/', - '.svn/' + ".git/", + ".svn/" ] }) .then(function(files) { diff --git a/lib/utils/git.js b/lib/utils/git.js index 6eb9681..e93c8f2 100644 --- a/lib/utils/git.js +++ b/lib/utils/git.js @@ -1,7 +1,5 @@ var Q = require("q"); var _ = require("lodash"); -var url = require("url"); -var tmp = require("tmp"); var path = require("path"); var crc = require("crc"); var exec = Q.denodeify(require("child_process").exec); @@ -102,11 +100,11 @@ function resolveFileFromGit(giturl) { // Resolve relative path return path.resolve(repo, giturl.filepath); }); -}; +} // Return root of git repo from a filepath function resolveGitRoot(filepath) { - var relativeToGit, repoId + var relativeToGit, repoId; // No git repo cloned, or file is not in a git repository if (!GIT_TMP || !pathUtil.isInRoot(GIT_TMP, filepath)) return null; @@ -118,7 +116,7 @@ function resolveGitRoot(filepath) { // Return an absolute file return path.resolve(GIT_TMP, repoId); -}; +} module.exports = { diff --git a/lib/utils/i18n.js b/lib/utils/i18n.js index c3253b7..f6001f9 100644 --- a/lib/utils/i18n.js +++ b/lib/utils/i18n.js @@ -4,7 +4,7 @@ var fs = require("fs"); var i18n = require("i18n"); -var I18N_PATH = path.resolve(__dirname, "../../theme/i18n/") +var I18N_PATH = path.resolve(__dirname, "../../theme/i18n/"); var DEFAULT_LANGUAGE = "en"; var LOCALES = _.map(fs.readdirSync(I18N_PATH), function(lang) { return path.basename(lang, ".json"); @@ -17,7 +17,7 @@ i18n.configure({ updateFiles: false }); -var compareLocales = function(lang, locale) { +function compareLocales(lang, locale) { var langMain = _.first(lang.split("-")); var langSecond = _.last(lang.split("-")); @@ -28,7 +28,7 @@ var compareLocales = function(lang, locale) { if (localeMain == langMain) return 50; if (localeSecond == langSecond) return 20; return 0; -}; +} var normalizeLanguage = _.memoize(function(lang) { var language = _.chain(LOCALES) @@ -37,7 +37,7 @@ var normalizeLanguage = _.memoize(function(lang) { return { locale: locale, score: compareLocales(lang, locale) - } + }; }) .filter(function(lang) { return lang.score > 0; @@ -49,25 +49,25 @@ var normalizeLanguage = _.memoize(function(lang) { return language || lang; }); -var translate = function(locale, phrase) { +function translate(locale, phrase) { var args = Array.prototype.slice.call(arguments, 2); return i18n.__.apply({}, [{ locale: locale, phrase: phrase }].concat(args)); -}; +} -var getCatalog = function(locale) { +function getCatalog(locale) { locale = normalizeLanguage(locale); return i18n.getCatalog(locale); -}; +} -var getLocales = function() { +function getLocales() { return LOCALES; -}; +} -var hasLocale = function(locale) { +function hasLocale(locale) { return _.contains(LOCALES, locale); } diff --git a/lib/utils/images.js b/lib/utils/images.js index 3bc650a..a82b0a1 100644 --- a/lib/utils/images.js +++ b/lib/utils/images.js @@ -1,9 +1,7 @@ var _ = require("lodash"); var Q = require("q"); var fs = require("./fs"); -var spawn = require('spawn-cmd').spawn; - -var links = require("./links"); +var spawn = require("spawn-cmd").spawn; // Convert a svg file var convertSVG = function(source, dest, options) { @@ -14,16 +12,16 @@ var convertSVG = function(source, dest, options) { }); - //var command = shellescape(['svgexport', source, dest]); - var child = spawn('svgexport', [source, dest]); + //var command = shellescape(["svgexport", source, dest]); + var child = spawn("svgexport", [source, dest]); child.on("error", function(error) { - if (error.code == "ENOENT") error = new Error("Need to install 'svgexport' using 'npm install svgexport -g'"); + if (error.code == "ENOENT") error = new Error("Need to install \"svgexport\" using \"npm install svgexport -g\""); return d.reject(error); }); child.on("close", function(code) { - if (code == 0 && fs.existsSync(dest)) { + if (code === 0 && fs.existsSync(dest)) { d.resolve(); } else { d.reject(new Error("Error converting "+source+" into "+dest)); diff --git a/lib/utils/links.js b/lib/utils/links.js index 61cdc9a..589e0d7 100644 --- a/lib/utils/links.js +++ b/lib/utils/links.js @@ -1,5 +1,5 @@ -var url = require('url'); -var path = require('path'); +var url = require("url"); +var path = require("path"); // Is the link an external link var isExternal = function(href) { @@ -33,7 +33,7 @@ var isAnchor = function(href) { // Normalize a path to be a link var normalizeLink = function(s) { - return s.replace(/\\/g, '/'); + return s.replace(/\\/g, "/"); }; // Relative to absolute path @@ -43,7 +43,7 @@ var normalizeLink = function(s) { var toAbsolute = function(_href, dir, outdir) { if (isExternal(_href)) return _href; - // Path '_href' inside the base folder + // Path "_href" inside the base folder var hrefInRoot = path.normalize(path.join(dir, _href)); if (_href[0] == "/") hrefInRoot = path.normalize(_href.slice(1)); diff --git a/lib/utils/logger.js b/lib/utils/logger.js index 5c1da8c..db3d90e 100644 --- a/lib/utils/logger.js +++ b/lib/utils/logger.js @@ -1,6 +1,6 @@ -var _ = require('lodash'); -var util = require('util'); -var color = require('bash-color'); +var _ = require("lodash"); +var util = require("util"); +var color = require("bash-color"); var LEVELS = { DEBUG: 0, @@ -19,7 +19,7 @@ var COLORS = { module.exports = function(_write, logLevel) { var logger = {}; - var lastChar = '\n'; + var lastChar = "\n"; if (_.isString(logLevel)) logLevel = LEVELS[logLevel.toUpperCase()]; // Write a simple message @@ -47,14 +47,14 @@ module.exports = function(_write, logLevel) { var args = Array.prototype.slice.apply(arguments, [1]); var msg = logger.format.apply(logger, args); - if (lastChar == '\n') { + if (lastChar == "\n") { msg = COLORS[levelKey](levelKey.toLowerCase()+":")+" "+msg; } return logger.write(msg); }; logger.logLn = function() { - if (lastChar != '\n') logger.write("\n"); + if (lastChar != "\n") logger.write("\n"); var args = Array.prototype.slice.apply(arguments); args.push("\n"); @@ -66,7 +66,7 @@ module.exports = function(_write, logLevel) { var args = Array.prototype.slice.apply(arguments, [1]); var msg = logger.format.apply(logger, args); if (arguments.length > 1) { - logger.logLn(level, color.green('>> ') + msg.trim().replace(/\n/g, color.green('\n>> '))); + logger.logLn(level, color.green(">> ") + msg.trim().replace(/\n/g, color.green("\n>> "))); } else { logger.log(level, color.green("OK"), "\n"); } @@ -77,7 +77,7 @@ module.exports = function(_write, logLevel) { return logger.log(level, color.red("ERROR")+"\n"); }; - _.each(_.omit(LEVELS, 'DISABLED'), function(level, levelKey) { + _.each(_.omit(LEVELS, "DISABLED"), function(level, levelKey) { levelKey = levelKey.toLowerCase(); logger[levelKey] = _.partial(logger.log, level); @@ -93,7 +93,7 @@ module.exports = function(_write, logLevel) { logger[levelKey].fail(); throw err; }); - } + }; }); return logger; diff --git a/lib/utils/navigation.js b/lib/utils/navigation.js index d825c2c..d07eb35 100644 --- a/lib/utils/navigation.js +++ b/lib/utils/navigation.js @@ -1,9 +1,9 @@ -var _ = require('lodash'); +var _ = require("lodash"); // Cleans up an article/chapter object -// remove 'articles' attributes +// remove "articles" attributes function clean(obj) { - return obj && _.omit(obj, ['articles']); + return obj && _.omit(obj, ["articles"]); } function flattenChapters(chapters) { diff --git a/lib/utils/page.js b/lib/utils/page.js index 5b4eca8..a17c6a2 100644 --- a/lib/utils/page.js +++ b/lib/utils/page.js @@ -1,18 +1,18 @@ -var Q = require('q'); -var _ = require('lodash'); -var url = require('url'); -var path = require('path'); -var cheerio = require('cheerio'); -var domSerializer = require('dom-serializer'); -var request = require('request'); +var Q = require("q"); +var _ = require("lodash"); +var url = require("url"); +var path = require("path"); +var cheerio = require("cheerio"); +var domSerializer = require("dom-serializer"); +var request = require("request"); var crc = require("crc"); -var links = require('./links'); -var imgUtils = require('./images'); -var fs = require('./fs'); -var batch = require('./batch'); +var links = require("./links"); +var imgUtils = require("./images"); +var fs = require("./fs"); +var batch = require("./batch"); -var parsableExtensions = require('gitbook-parsers').extensions; +var parsableExtensions = require("gitbook-parsers").extensions; // Render a cheerio dom as html var renderDom = function($, dom, options) { @@ -40,7 +40,8 @@ function replaceText($, el, search, replace, text_only ) { if ( node ) { // Loop over all childNodes. - do { + while (node) { + // Only process text nodes. if ( node.nodeType === 3 ) { @@ -58,7 +59,7 @@ function replaceText($, el, search, replace, text_only ) { // robust way. $(node).before( new_val ); - // Don't remove the node yet, or the loop will lose its place. + // Don"t remove the node yet, or the loop will lose its place. remove.push( node ); } else { // The new value contains no HTML, so it can be set in this @@ -68,17 +69,18 @@ function replaceText($, el, search, replace, text_only ) { } } - } while ( node = node.nextSibling ); + node = node.nextSibling; + } } // Time to remove those elements! - remove.length && $(remove).remove(); + if (remove.length) $(remove).remove(); }); -}; +} function pregQuote( str ) { - return (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1"); -}; + return (str+"").replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1"); +} // Adapt an html snippet to be relative to a base folder @@ -107,15 +109,16 @@ function normalizeHtml(src, options) { // Generate filename dest = "/"+fs.getUniqueFilename(outputRoot, dest); - svgContent[dest] = '<?xml version="1.0" encoding="UTF-8"?>'+content; + svgContent[dest] = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+content; $(this).replaceWith($("<img>").attr("src", dest)); }); } // Find images to normalize $("img").each(function() { - var origin = undefined; + var origin; var src = $(this).attr("src"); + if (!src) return; var isExternal = links.isExternal(src); @@ -150,7 +153,7 @@ function normalizeHtml(src, options) { dest = links.join(path.dirname(srcAbs), path.basename(srcAbs, ext)+".png"); dest = dest[0] == "/"? dest.slice(1) : dest; - // Get a name that doesn't exists + // Get a name that doesn"t exists dest = fs.getUniqueFilename(outputRoot, dest); options.book.log.debug.ln("detect invalid image (will be converted to png):", srcAbs); @@ -205,9 +208,9 @@ function normalizeHtml(src, options) { // If md/adoc/rst files is not in summary // or for ebook, signal all files that are outside the summary - else if (_.contains(parsableExtensions, path.extname(absolutePath)) - || _.contains(['epub', 'pdf', 'mobi'], options.book.options.generator)) { - options.book.log.warn.ln("page", options.input, "contains an hyperlink to resource outside spine '"+href+"'"); + else if (_.contains(parsableExtensions, path.extname(absolutePath)) || + _.contains(["epub", "pdf", "mobi"], options.book.options.generator)) { + options.book.log.warn.ln("page", options.input, "contains an hyperlink to resource outside spine \""+href+"\""); } // Transform as absolute @@ -241,7 +244,7 @@ function normalizeHtml(src, options) { .value(); var source = $(this).text(); - var html = options.book.template.applyBlock('code', { + var html = options.book.template.applyBlock("code", { body: source, kwargs: { language: lang @@ -255,8 +258,9 @@ function normalizeHtml(src, options) { var glossary = _.sortBy(options.glossary, function(term) { return -term.name.length; }); + _.each(glossary, function(term) { - var r = new RegExp( "\\b(" + pregQuote(term.name.toLowerCase()) + ")\\b" , 'gi' ); + var r = new RegExp( "\\b(" + pregQuote(term.name.toLowerCase()) + ")\\b" , "gi" ); var includedInFiles = false; $("*").each(function() { @@ -270,7 +274,7 @@ function normalizeHtml(src, options) { term.files = term.files || []; term.files.push(options.navigation[options.input]); } - return "<a href='"+links.toAbsolute("/GLOSSARY.html", options.base, options.output)+"#"+term.id+"' class='glossary-term' title='"+_.escape(term.description)+"'>"+match+"</a>"; + return "<a href=\""+links.toAbsolute("/GLOSSARY.html", options.base, options.output) + "#" + term.id+"\" class=\"glossary-term\" title=\""+_.escape(term.description)+"\">"+match+"</a>"; }); }); }); @@ -279,7 +283,7 @@ function normalizeHtml(src, options) { html: renderDom($), images: toConvert }; -}; +} // Convert svg images to png function convertImages(images, options) { @@ -304,7 +308,7 @@ function convertImages(images, options) { .fail(function(err) { if (!_.isError(err)) err = new Error(err); - err.message = 'Fail downloading '+image.origin+': '+err.message; + err.message = "Fail downloading "+image.origin+": "+err.message; throw err; }); }) @@ -327,8 +331,7 @@ function convertImages(images, options) { .then(function() { options.book.log.debug.ok(images.length+" images converted with success"); }); -}; - +} // Adapt page content to be relative to a base folder function normalizePage(sections, options) { @@ -361,7 +364,7 @@ function normalizePage(sections, options) { sections = _.map(sections, function(section) { if (section.type != "normal") return section; - var out = normalizeHtml(section.content, options);; + var out = normalizeHtml(section.content, options); toConvert = toConvert.concat(out.images); section.content = out.html; @@ -370,11 +373,11 @@ function normalizePage(sections, options) { return Q() .then(function() { - toConvert = _.uniq(toConvert, 'source'); + toConvert = _.uniq(toConvert, "source"); return convertImages(toConvert, options); }) .thenResolve(sections); -}; +} // Extract text from sections function extractText(sections) { @@ -388,7 +391,7 @@ function extractText(sections) { return prev; }, ""); -}; +} module.exports = { normalize: normalizePage, diff --git a/lib/utils/path.js b/lib/utils/path.js index d5b98f7..5285896 100644 --- a/lib/utils/path.js +++ b/lib/utils/path.js @@ -1,5 +1,5 @@ var _ = require("lodash"); -var path = require('path'); +var path = require("path"); // Return true if file path is inside a folder function isInRoot(root, filename) { @@ -10,28 +10,29 @@ function isInRoot(root, filename) { // Resolve paths in a specific folder // Throw error if file is outside this folder function resolveInRoot(root) { - var input = _.chain(arguments) + var input, result, err; + + input = _.chain(arguments) .toArray() .slice(1) - .reduce(function(current, p, i) { - // Handle path relative to book root ('/README.md') - if (p[0] == '/' || p[0] == '\\') return p.slice(1); + .reduce(function(current, p) { + // Handle path relative to book root ("/README.md") + if (p[0] == "/" || p[0] == "\\") return p.slice(1); return current? path.join(current, p) : path.normalize(p); - }, '') + }, "") .value(); - var result = path.resolve(root, input); + result = path.resolve(root, input); if (!isInRoot(root, result)) { - err = new Error("EACCESS: '" + result + "' not in '" + root + "'"); + err = new Error("EACCESS: \"" + result + "\" not in \"" + root + "\""); err.code = "EACCESS"; throw err; } - return result -}; - + return result; +} module.exports = { isInRoot: isInRoot, diff --git a/lib/utils/progress.js b/lib/utils/progress.js index 9669d86..78821ad 100644 --- a/lib/utils/progress.js +++ b/lib/utils/progress.js @@ -1,7 +1,7 @@ var _ = require("lodash"); // Returns from a navigation and a current file, a snapshot of current detailed state -var calculProgress = function(navigation, current) { +function calculProgress(navigation, current) { var n = _.size(navigation); var percent = 0, prevPercent = 0, currentChapter = null; var done = true; diff --git a/lib/utils/server.js b/lib/utils/server.js index 2b97fe8..1d6822f 100644 --- a/lib/utils/server.js +++ b/lib/utils/server.js @@ -1,11 +1,9 @@ -var Q = require('q'); -var _ = require('lodash'); - -var events = require('events'); -var http = require('http'); -var send = require('send'); -var util = require('util'); -var url = require('url'); +var Q = require("q"); +var events = require("events"); +var http = require("http"); +var send = require("send"); +var util = require("util"); +var url = require("url"); var Server = function() { this.running = null; @@ -17,7 +15,7 @@ util.inherits(Server, events.EventEmitter); // Return true if the server is running Server.prototype.isRunning = function() { - return this.running != null; + return !!this.running; }; // Stop the server @@ -57,25 +55,25 @@ Server.prototype.start = function(dir, port) { res.end(err.message); } - // Redirect to directory's index.html + // Redirect to directory"s index.html function redirect() { res.statusCode = 301; - res.setHeader('Location', req.url + '/'); - res.end('Redirecting to ' + req.url + '/'); + res.setHeader("Location", req.url + "/"); + res.end("Redirecting to " + req.url + "/"); } // Send file send(req, url.parse(req.url).pathname) .root(dir) - .on('error', error) - .on('directory', redirect) + .on("error", error) + .on("directory", redirect) .pipe(res); }); - that.running.on('connection', function (socket) { + that.running.on("connection", function (socket) { that.sockets.push(socket); socket.setTimeout(4000); - socket.on('close', function () { + socket.on("close", function () { that.sockets.splice(that.sockets.indexOf(socket), 1); }); }); @@ -91,6 +89,6 @@ Server.prototype.start = function(dir, port) { return d.promise; }); -} +}; module.exports = Server; diff --git a/lib/utils/string.js b/lib/utils/string.js index 72a9ca0..caa2364 100644 --- a/lib/utils/string.js +++ b/lib/utils/string.js @@ -1,7 +1,7 @@ var _ = require("lodash"); function escapeShellArg(arg) { - var ret = ''; + var ret = ""; ret = arg.replace(/"/g, '\\"'); @@ -11,7 +11,7 @@ function escapeShellArg(arg) { function optionsToShellArgs(options) { return _.chain(options) .map(function(value, key) { - if (value == null || value === false) return null; + if (value === null || value === undefined || value === false) return null; if (value === true) return key; return key+"="+escapeShellArg(value); }) diff --git a/lib/utils/watch.js b/lib/utils/watch.js index 3e73e47..4d1a752 100644 --- a/lib/utils/watch.js +++ b/lib/utils/watch.js @@ -1,9 +1,9 @@ -var Q = require('q'); -var _ = require('lodash'); -var path = require('path'); -var chokidar = require('chokidar'); +var Q = require("q"); +var _ = require("lodash"); +var path = require("path"); +var chokidar = require("chokidar"); -var parsers = require('gitbook-parsers') +var parsers = require("gitbook-parsers"); function watch(dir) { var d = Q.defer(); @@ -19,7 +19,7 @@ function watch(dir) { var watcher = chokidar.watch(toWatch, { cwd: dir, - ignored: '_book/**', + ignored: "_book/**", ignoreInitial: true }); diff --git a/test/assertions.js b/test/assertions.js index f81645b..7e14ecb 100644 --- a/test/assertions.js +++ b/test/assertions.js @@ -1,27 +1,27 @@ -var _ = require('lodash'); -var fs = require('fs'); -var path = require('path'); -var should = require('should'); -var cheerio = require('cheerio'); +var _ = require("lodash"); +var fs = require("fs"); +var path = require("path"); +var should = require("should"); +var cheerio = require("cheerio"); -should.Assertion.add('file', function(file, description) { - this.params = { actual: this.obj.toString(), operator: 'have file ' + file, message: description }; +should.Assertion.add("file", function(file, description) { + this.params = { actual: this.obj.toString(), operator: "have file " + file, message: description }; - this.obj.should.have.property('options').which.is.an.Object; - this.obj.options.should.have.property('output').which.is.a.String; + this.obj.should.have.property("options").which.is.an.Object(); + this.obj.options.should.have.property("output").which.is.a.String(); this.assert(fs.existsSync(path.resolve(this.obj.options.output, file))); }); -should.Assertion.add('jsonfile', function(file, description) { - this.params = { actual: this.obj.toString(), operator: 'have valid jsonfile ' + file, message: description }; +should.Assertion.add("jsonfile", function(file, description) { + this.params = { actual: this.obj.toString(), operator: "have valid jsonfile " + file, message: description }; - this.obj.should.have.property('options').which.is.an.Object; - this.obj.options.should.have.property('output').which.is.a.String; + this.obj.should.have.property("options").which.is.an.Object(); + this.obj.options.should.have.property("output").which.is.a.String(); this.assert(JSON.parse(fs.readFileSync(path.resolve(this.obj.options.output, file), { encoding: "utf-8" }))); }); -should.Assertion.add('html', function(rules, description) { - this.params = { actual: "HTML string", operator: 'valid html', message: description }; +should.Assertion.add("html", function(rules, description) { + this.params = { actual: "HTML string", operator: "valid html", message: description }; var $ = cheerio.load(this.obj); _.each(rules, function(validations, query) { @@ -60,7 +60,7 @@ should.Assertion.add('html', function(rules, description) { // Test attributes _.each(validations.attributes, function(value, name) { var attr = $el.attr(name); - should(attr).be.ok; + should(attr).be.ok(); attr.should.be.equal(value); }); }); diff --git a/test/codehighlighting.js b/test/codehighlighting.js index e35f37e..d79fc85 100644 --- a/test/codehighlighting.js +++ b/test/codehighlighting.js @@ -1,16 +1,14 @@ -var _ = require('lodash'); -var should = require('should'); -var path = require('path'); -var fs = require('fs'); +var path = require("path"); +var fs = require("fs"); -var Plugin = require('../lib/plugin'); -var PLUGINS_ROOT = path.resolve(__dirname, 'plugins'); +var Plugin = require("../lib/plugin"); +var PLUGINS_ROOT = path.resolve(__dirname, "plugins"); -describe('Code Highlighting', function () { +describe("Code Highlighting", function () { var book, PAGE; before(function() { - return books.generate('highlight', 'website', { + return books.generate("highlight", "website", { prepare: function(_book) { book = _book; @@ -28,29 +26,29 @@ describe('Code Highlighting', function () { }); }); - it('should correctly replace highlighting', function() { + it("should correctly replace highlighting", function() { PAGE.should.be.html({ "code": { index: 0, - text: 'code_test 1\n_code' + text: "code_test 1\n_code" } }); }); - it('should correctly replace highlighting with language', function() { + it("should correctly replace highlighting with language", function() { PAGE.should.be.html({ "code": { index: 1, - text: 'lang_test 2\n_lang' + text: "lang_test 2\n_lang" } }); }); - it('should correctly replace highlighting for inline code', function() { + it("should correctly replace highlighting for inline code", function() { PAGE.should.be.html({ "code": { index: 2, - text: 'code_test 3_code' + text: "code_test 3_code" } }); }); diff --git a/test/configuration.js b/test/configuration.js index 2cff26e..c96c10d 100644 --- a/test/configuration.js +++ b/test/configuration.js @@ -1,40 +1,37 @@ -var fs = require('fs'); -var path = require('path'); - -describe('Configuration', function () { - it('should extract default title from README', function() { +describe("Configuration", function () { + it("should extract default title from README", function() { return books.parse("basic") .then(function(book) { book.options.title.should.be.equal("Readme"); }); }); - it('should extract default description from README', function() { + it("should extract default description from README", function() { return books.parse("basic") .then(function(book) { book.options.description.should.be.equal("Default description for the book."); }); }); - it('should correctly load from json (book.json)', function() { + it("should correctly load from json (book.json)", function() { return books.parse("config-json") .then(function(book) { book.options.title.should.be.equal("json-config"); }); }); - it('should correctly load from JavaScript (book.js)', function() { + it("should correctly load from JavaScript (book.js)", function() { return books.parse("config-js") .then(function(book) { book.options.title.should.be.equal("js-config"); }); }); - it('should provide configuration on book.config.get', function() { + it("should provide configuration on book.config.get", function() { return books.parse("basic") .then(function(book) { - book.config.get('description').should.be.equal("Default description for the book."); - book.getConfig('description').should.be.equal("Default description for the book."); + book.config.get("description").should.be.equal("Default description for the book."); + book.getConfig("description").should.be.equal("Default description for the book."); }); }); }); diff --git a/test/conrefs.js b/test/conrefs.js index 7e044f5..4f654b0 100644 --- a/test/conrefs.js +++ b/test/conrefs.js @@ -1,7 +1,7 @@ -var fs = require('fs'); -var path = require('path'); +var fs = require("fs"); +var path = require("path"); -describe('ConRefs', function () { +describe("ConRefs", function () { var book, readme; before(function() { @@ -16,7 +16,7 @@ describe('ConRefs', function () { }); }); - it('should handle local references', function() { + it("should handle local references", function() { readme.should.be.html({ ".page-inner p#t1": { count: 1, @@ -26,7 +26,7 @@ describe('ConRefs', function () { }); }); - it('should handle local references with absolute paths', function() { + it("should handle local references with absolute paths", function() { readme.should.be.html({ ".page-inner p#t2": { count: 1, @@ -36,7 +36,7 @@ describe('ConRefs', function () { }); }); - it('should correctly include file from git reference', function() { + it("should correctly include file from git reference", function() { readme.should.be.html({ ".page-inner p#t3": { count: 1, @@ -46,7 +46,7 @@ describe('ConRefs', function () { }); }); - it('should correctly handle deep include in git reference', function() { + it("should correctly handle deep include in git reference", function() { readme.should.be.html({ ".page-inner p#t4": { count: 1, @@ -56,7 +56,7 @@ describe('ConRefs', function () { }); }); - it('should correctly handle absolute include in git reference', function() { + it("should correctly handle absolute include in git reference", function() { readme.should.be.html({ ".page-inner p#t5": { count: 1, diff --git a/test/ebook.js b/test/ebook.js index 033fd04..b065ae7 100644 --- a/test/ebook.js +++ b/test/ebook.js @@ -1,8 +1,8 @@ -var fs = require('fs'); -var path = require('path'); +var fs = require("fs"); +var path = require("path"); -describe('eBook generator', function () { - describe('Basic Book', function() { +describe("eBook generator", function () { + describe("Basic Book", function() { var book; before(function() { @@ -12,17 +12,17 @@ describe('eBook generator', function () { }); }); - it('should correctly output a SUMMARY.html', function() { + it("should correctly output a SUMMARY.html", function() { book.should.have.file("SUMMARY.html"); }); - it('should correctly copy assets', function() { + it("should correctly copy assets", function() { book.should.have.file("gitbook"); book.should.have.file("gitbook/style.css"); }); }); - describe('Custom styles', function() { + describe("Custom styles", function() { var book; before(function() { @@ -32,7 +32,7 @@ describe('eBook generator', function () { }); }); - it('should remove default print.css', function() { + it("should remove default print.css", function() { var PAGE = fs.readFileSync( path.join(book.options.output, "index.html"), { encoding: "utf-8" } @@ -46,21 +46,21 @@ describe('eBook generator', function () { }); PAGE.should.be.html({ - "link[href='./styles/print.css']": { + "link[href=\"./styles/print.css\"]": { count: 1 } }); PAGE.should.be.html({ - "link[href='gitbook/plugins/gitbook-plugin-highlight/ebook.css']": { + "link[href=\"gitbook/plugins/gitbook-plugin-highlight/ebook.css\"]": { count: 1 } }); }); - it('should correctly print.css', function() { + it("should correctly print.css", function() { book.should.have.file("styles"); book.should.have.file("styles/print.css"); }); - }) + }); }); diff --git a/test/git.js b/test/git.js index f03bec2..6fd6b41 100644 --- a/test/git.js +++ b/test/git.js @@ -1,8 +1,8 @@ -var should = require('should'); -var git = require('../lib/utils/git'); +var should = require("should"); +var git = require("../lib/utils/git"); -describe('GIT parser and getter', function () { - it('should correctly parse an https url', function() { +describe("GIT parser and getter", function () { + it("should correctly parse an https url", function() { var parts = git.parseUrl("git+https://gist.github.com/69ea4542e4c8967d2fa7.git/test.md"); should.exist(parts); @@ -11,7 +11,7 @@ describe('GIT parser and getter', function () { parts.filepath.should.be.equal("test.md"); }); - it('should correctly parse an https url with a reference', function() { + it("should correctly parse an https url with a reference", function() { var parts = git.parseUrl("git+https://gist.github.com/69ea4542e4c8967d2fa7.git/test.md#0.1.2"); should.exist(parts); @@ -20,7 +20,7 @@ describe('GIT parser and getter', function () { parts.filepath.should.be.equal("test.md"); }); - it('should correctly parse an ssh url', function() { + it("should correctly parse an ssh url", function() { var parts = git.parseUrl("git+git@github.com:GitbookIO/gitbook.git/directory/README.md#e1594cde2c32e4ff48f6c4eff3d3d461743d74e1"); should.exist(parts); diff --git a/test/glossary.js b/test/glossary.js index fb573d9..f0f31a5 100644 --- a/test/glossary.js +++ b/test/glossary.js @@ -1,8 +1,8 @@ -var fs = require('fs'); -var path = require('path'); +var fs = require("fs"); +var path = require("path"); -describe('Glossary', function () { - describe('Parsing', function() { +describe("Glossary", function () { + describe("Parsing", function() { var book; before(function() { @@ -12,13 +12,13 @@ describe('Glossary', function () { }); }); - it('should correctly list items', function() { + it("should correctly list items", function() { book.should.have.property("glossary"); book.glossary.should.have.lengthOf(3); }); }); - describe('Generation', function() { + describe("Generation", function() { var book; before(function() { @@ -28,11 +28,11 @@ describe('Glossary', function () { }); }); - it('should correctly generate a GLOSSARY.html', function() { + it("should correctly generate a GLOSSARY.html", function() { book.should.have.file("GLOSSARY.html"); }); - describe('Page Integration', function() { + describe("Page Integration", function() { var readme, page; before(function() { @@ -46,9 +46,9 @@ describe('Glossary', function () { ); }); - it('should correctly replaced terms by links', function() { + it("should correctly replaced terms by links", function() { readme.should.be.html({ - ".page-inner a[href='GLOSSARY.html#test']": { + ".page-inner a[href=\"GLOSSARY.html#test\"]": { count: 1, text: "test", attributes: { @@ -58,15 +58,15 @@ describe('Glossary', function () { }); }); - it('should correctly replaced terms by links (relative)', function() { + it("should correctly replaced terms by links (relative)", function() { page.should.be.html({ - ".page-inner a[href='../GLOSSARY.html#test']": { + ".page-inner a[href=\"../GLOSSARY.html#test\"]": { count: 1 } }); }); - it('should not replace terms in codeblocks', function() { + it("should not replace terms in codeblocks", function() { readme.should.be.html({ ".page-inner code a": { count: 0 @@ -74,9 +74,9 @@ describe('Glossary', function () { }); }); - it('should correctly select the longest term', function() { + it("should correctly select the longest term", function() { readme.should.be.html({ - ".page-inner a[href='GLOSSARY.html#test_long']": { + ".page-inner a[href=\"GLOSSARY.html#test_long\"]": { count: 1, text: "test long" } diff --git a/test/helper.js b/test/helper.js index f4432a9..95619df 100644 --- a/test/helper.js +++ b/test/helper.js @@ -1,13 +1,11 @@ -var os = require('os'); -var path = require('path'); -var Q = require('q'); -var fs = require('fs'); -var _ = require('lodash'); -var should = require('should'); +var os = require("os"); +var path = require("path"); +var Q = require("q"); +var _ = require("lodash"); -var fsUtil = require('../lib/utils/fs'); -var Book = require('../').Book; -var LOG_LEVELS = require('../').LOG_LEVELS; +var fsUtil = require("../lib/utils/fs"); +var Book = require("../").Book; +var LOG_LEVELS = require("../").LOG_LEVELS; require("./assertions"); @@ -61,16 +59,14 @@ global.books = { // Cleanup all tests after(function() { return _.chain(BOOKS) - .map(function(types, bookId) { + .map(function(types) { return _.values(types); }) .flatten() .reduce(function(prev, book) { return prev.then(function() { return fsUtil.remove(book.options.output); - }) + }); }, Q()) .value(); }); - - diff --git a/test/images.js b/test/images.js index 75bc529..de45066 100644 --- a/test/images.js +++ b/test/images.js @@ -1,9 +1,9 @@ -var fs = require('fs'); -var _ = require('lodash'); -var path = require('path'); -var cheerio = require('cheerio'); +var fs = require("fs"); +var _ = require("lodash"); +var path = require("path"); +var cheerio = require("cheerio"); -describe('Images', function () { +describe("Images", function () { var book, readme, $, $img, srcs; before(function() { @@ -17,38 +17,40 @@ describe('Images', function () { ); $ = cheerio.load(readme); $img = $("img"); - srcs = $img.map(function() { return $(this).attr("src"); }) + srcs = $img.map(function() { + return $(this).attr("src"); + }); }); }); - it('should detect all images', function() { + it("should detect all images", function() { _.uniq(srcs).should.have.lengthOf(4); }); - it('should keep image tags', function() { + it("should keep image tags", function() { srcs.should.have.lengthOf(5); }); - it('should not have .svg files', function() { + it("should not have .svg files", function() { _.each(srcs, function(src) { path.extname(src).should.not.equal(".svg"); }); }); - it('should correctly convert svg images to png', function() { + it("should correctly convert svg images to png", function() { _.each(srcs, function(src) { book.should.have.file(src); }); }); - it('should handle relative paths', function() { + it("should handle relative paths", function() { var PAGE = fs.readFileSync( path.join(book.options.output, "folder/PAGE.html"), { encoding: "utf-8" } ); PAGE.should.be.html({ - "img[src='../test.png']": { + "img[src=\"../test.png\"]": { count: 1 } }); diff --git a/test/init.js b/test/init.js index 8415b20..7e5ffee 100644 --- a/test/init.js +++ b/test/init.js @@ -1,11 +1,11 @@ -var fs = require('fs'); -var path = require('path'); -var should = require('should'); +var fs = require("fs"); +var path = require("path"); +var should = require("should"); -var Book = require('../').Book; -var LOG_LEVELS = require('../').LOG_LEVELS; +var Book = require("../").Book; +var LOG_LEVELS = require("../").LOG_LEVELS; -describe('Init Books', function () { +describe("Init Books", function () { var initRoot; before(function() { @@ -15,10 +15,10 @@ describe('Init Books', function () { }); }); - it('should create all chapters', function() { - should(fs.existsSync(path.resolve(initRoot, "hello.md"))).be.ok; - should(fs.existsSync(path.resolve(initRoot, "hello2.md"))).be.ok; - should(fs.existsSync(path.resolve(initRoot, "hello3/hello4.md"))).be.ok; - should(fs.existsSync(path.resolve(initRoot, "hello3/hello5/hello6.md"))).be.ok; + it("should create all chapters", function() { + should(fs.existsSync(path.resolve(initRoot, "hello.md"))).be.ok(); + should(fs.existsSync(path.resolve(initRoot, "hello2.md"))).be.ok(); + should(fs.existsSync(path.resolve(initRoot, "hello3/hello4.md"))).be.ok(); + should(fs.existsSync(path.resolve(initRoot, "hello3/hello5/hello6.md"))).be.ok(); }); }); diff --git a/test/json.js b/test/json.js index 758cfd7..311c80a 100644 --- a/test/json.js +++ b/test/json.js @@ -1,8 +1,8 @@ -var fs = require('fs'); -var path = require('path'); +var fs = require("fs"); +var path = require("path"); -describe('JSON generator', function () { - describe('Basic Book', function() { +describe("JSON generator", function () { + describe("Basic Book", function() { var book; before(function() { @@ -12,15 +12,15 @@ describe('JSON generator', function () { }); }); - it('should correctly output a README.json', function() { + it("should correctly output a README.json", function() { book.should.have.file("README.json"); }); - it('should output a valid json', function() { + it("should output a valid json", function() { book.should.have.jsonfile("README.json"); }); - describe('Page Format', function() { + describe("Page Format", function() { var page; before(function() { @@ -32,25 +32,25 @@ describe('JSON generator', function () { ); }); - it('should contains valid section', function() { + it("should contains valid section", function() { page.should.have.property("sections").with.lengthOf(1); - page.sections[0].should.have.property("content").which.is.a.String; + page.sections[0].should.have.property("content").which.is.a.String(); page.sections[0].should.have.property("type", "normal"); }); - it('should contains valid progress', function() { + it("should contains valid progress", function() { page.should.have.property("progress"); page.progress.should.have.property("chapters").with.lengthOf(1); page.progress.should.have.property("current"); }); - it('should contains no languages', function() { + it("should contains no languages", function() { page.should.have.property("langs").with.lengthOf(0); }); }); }); - describe('Multilingual Book', function() { + describe("Multilingual Book", function() { var book; before(function() { @@ -60,19 +60,19 @@ describe('JSON generator', function () { }); }); - it('should correctly output READMEs', function() { + it("should correctly output READMEs", function() { book.should.have.file("README.json"); book.should.have.file("en/README.json"); book.should.have.file("fr/README.json"); }); - it('should output valid json', function() { + it("should output valid json", function() { book.should.have.jsonfile("README.json"); book.should.have.jsonfile("en/README.json"); book.should.have.jsonfile("fr/README.json"); }); - describe('Page Format', function() { + describe("Page Format", function() { var page; before(function() { @@ -84,7 +84,7 @@ describe('JSON generator', function () { ); }); - it('should contains no languages', function() { + it("should contains no languages", function() { page.should.have.property("langs").with.lengthOf(2); }); }); diff --git a/test/languages.js b/test/languages.js index abdc5dd..0bde347 100644 --- a/test/languages.js +++ b/test/languages.js @@ -1,8 +1,5 @@ -var fs = require('fs'); -var path = require('path'); - -describe('Languages', function () { - describe('Parsing', function() { +describe("Languages", function () { + describe("Parsing", function() { var book; before(function() { @@ -12,7 +9,7 @@ describe('Languages', function () { }); }); - it('should correctly list languages', function() { + it("should correctly list languages", function() { book.should.have.property("books"); book.books.should.have.lengthOf(2); @@ -21,7 +18,7 @@ describe('Languages', function () { }); }); - describe('Generation', function() { + describe("Generation", function() { var book; before(function() { @@ -31,7 +28,7 @@ describe('Languages', function () { }); }); - it('should correctly create books', function() { + it("should correctly create books", function() { book.should.have.file("index.html"); book.should.have.file("en/index.html"); book.should.have.file("fr/index.html"); diff --git a/test/links.js b/test/links.js index 1d83511..baca9d1 100644 --- a/test/links.js +++ b/test/links.js @@ -1,13 +1,11 @@ -var should = require('should'); -var fs = require('fs'); -var _ = require('lodash'); -var path = require('path'); -var cheerio = require('cheerio'); +var fs = require("fs"); +var path = require("path"); +var cheerio = require("cheerio"); var links = require("../lib/utils/links"); -describe('Links', function () { - it('should correctly test external links', function() { +describe("Links", function () { + it("should correctly test external links", function() { links.isExternal("http://google.fr").should.be.exactly(true); links.isExternal("https://google.fr").should.be.exactly(true); links.isExternal("test.md").should.be.exactly(false); @@ -15,32 +13,32 @@ describe('Links', function () { links.isExternal("/folder/test.md").should.be.exactly(false); }); - it('should correctly detect anchor links', function() { + it("should correctly detect anchor links", function() { links.isAnchor("#test").should.be.exactly(true); links.isAnchor(" #test").should.be.exactly(true); links.isAnchor("https://google.fr#test").should.be.exactly(false); links.isAnchor("test.md#test").should.be.exactly(false); }); - describe('toAbsolute', function() { - it('should correctly transform as absolute', function() { + describe("toAbsolute", function() { + it("should correctly transform as absolute", function() { links.toAbsolute("http://google.fr").should.be.equal("http://google.fr"); links.toAbsolute("test.md", "./", "./").should.be.equal("test.md"); links.toAbsolute("folder/test.md", "./", "./").should.be.equal("folder/test.md"); }); - it('should correctly handle windows path', function() { + it("should correctly handle windows path", function() { links.toAbsolute("folder\\test.md", "./", "./").should.be.equal("folder/test.md"); }); - it('should correctly handle absolute path', function() { + it("should correctly handle absolute path", function() { links.toAbsolute("/test.md", "./", "./").should.be.equal("test.md"); links.toAbsolute("/test.md", "test", "test").should.be.equal("../test.md"); links.toAbsolute("/sub/test.md", "test", "test").should.be.equal("../sub/test.md"); }); }); - describe('page', function() { + describe("page", function() { var book; before(function() { @@ -50,7 +48,7 @@ describe('Links', function () { }); }); - it('should correctly replace relative links', function() { + it("should correctly replace relative links", function() { var readme = fs.readFileSync( path.join(book.options.output, "folder1/index.html"), { encoding: "utf-8" } @@ -58,8 +56,8 @@ describe('Links', function () { var $ = cheerio.load(readme); var $a = $(".page-inner a"); - $a.attr('href').should.be.exactly("../folder2/index.html"); - }) + $a.attr("href").should.be.exactly("../folder2/index.html"); + }); }); }); diff --git a/test/navigation.js b/test/navigation.js index ddcc86e..9118b3c 100644 --- a/test/navigation.js +++ b/test/navigation.js @@ -1,6 +1,6 @@ -var should = require('should'); +var should = require("should"); -describe('Navigation', function () { +describe("Navigation", function () { var book; before(function() { @@ -10,52 +10,52 @@ describe('Navigation', function () { }); }); - it('should correctly parse navigation as a map', function() { + it("should correctly parse navigation as a map", function() { book.should.have.property("navigation"); book.navigation.should.have.property("README.md"); book.navigation.should.have.property("README.md"); }); - it('should correctly include filenames', function() { + it("should correctly include filenames", function() { book.navigation.should.have.property("README.md"); book.navigation.should.have.property("PAGE1.md"); book.navigation.should.have.property("folder/PAGE2.md"); book.navigation.should.not.have.property("NOTFOUND.md"); }); - it('should correctly detect next/prev for README', function() { - var README = book.navigation['README.md']; + it("should correctly detect next/prev for README", function() { + var README = book.navigation["README.md"]; README.index.should.equal(0); - README.should.have.property('next'); + README.should.have.property("next"); should(README.prev).not.be.ok(); - README.next.should.have.property('path'); - README.next.path.should.equal('PAGE1.md'); + README.next.should.have.property("path"); + README.next.path.should.equal("PAGE1.md"); }); - it('should correctly detect next/prev a page', function() { - var PAGE = book.navigation['PAGE1.md']; + it("should correctly detect next/prev a page", function() { + var PAGE = book.navigation["PAGE1.md"]; PAGE.index.should.equal(1); - PAGE.should.have.property('next'); - PAGE.should.have.property('prev'); + PAGE.should.have.property("next"); + PAGE.should.have.property("prev"); - PAGE.prev.should.have.property('path'); - PAGE.prev.path.should.equal('README.md'); + PAGE.prev.should.have.property("path"); + PAGE.prev.path.should.equal("README.md"); - PAGE.next.should.have.property('path'); - PAGE.next.path.should.equal('folder/PAGE2.md'); + PAGE.next.should.have.property("path"); + PAGE.next.path.should.equal("folder/PAGE2.md"); }); - it('should correctly detect next/prev for last page', function() { - var PAGE = book.navigation['folder/PAGE2.md']; + it("should correctly detect next/prev for last page", function() { + var PAGE = book.navigation["folder/PAGE2.md"]; PAGE.index.should.equal(2); - PAGE.should.have.property('prev'); + PAGE.should.have.property("prev"); should(PAGE.next).not.be.ok(); - PAGE.prev.should.have.property('path'); - PAGE.prev.path.should.equal('PAGE1.md'); + PAGE.prev.should.have.property("path"); + PAGE.prev.path.should.equal("PAGE1.md"); }); }); diff --git a/test/plugins.js b/test/plugins.js index 6d5b9de..e6df389 100644 --- a/test/plugins.js +++ b/test/plugins.js @@ -1,13 +1,12 @@ -var _ = require('lodash'); -var should = require('should'); -var path = require('path'); -var fs = require('fs'); +var _ = require("lodash"); +var should = require("should"); +var path = require("path"); -var Plugin = require('../lib/plugin'); +var Plugin = require("../lib/plugin"); var parsers = require("gitbook-parsers"); -var PLUGINS_ROOT = path.resolve(__dirname, 'plugins'); +var PLUGINS_ROOT = path.resolve(__dirname, "plugins"); -describe('Plugins', function () { +describe("Plugins", function () { var book; before(function() { @@ -17,7 +16,7 @@ describe('Plugins', function () { }); }); - describe('Invalid', function() { + describe("Invalid", function() { var plugin; before(function() { @@ -25,12 +24,12 @@ describe('Plugins', function () { plugin.load("./invalid", PLUGINS_ROOT); }); - it('should be detected', function() { + it("should be detected", function() { should(plugin.isValid()).be.exactly(false); }); }); - describe('Empty', function() { + describe("Empty", function() { var plugin; before(function() { @@ -38,11 +37,11 @@ describe('Plugins', function () { plugin.load("./empty", PLUGINS_ROOT); }); - it('should valid a plugin', function() { + it("should valid a plugin", function() { should(plugin.isValid()).be.exactly(true); }); - it('should return an empty list of resources', function() { + it("should return an empty list of resources", function() { return plugin.getResources() .then(function(resources) { _.each(Plugin.RESOURCES, function(resName) { @@ -52,7 +51,7 @@ describe('Plugins', function () { }); }); - describe('Resources', function() { + describe("Resources", function() { var plugin; before(function() { @@ -62,45 +61,45 @@ describe('Plugins', function () { return book.plugins.load(plugin); }); - it('should valid a plugin', function() { + it("should valid a plugin", function() { should(plugin.isValid()).be.exactly(true); }); - describe('Website', function() { - it('should return a valid list of resources', function() { + describe("Website", function() { + it("should return a valid list of resources", function() { return plugin.getResources("website") .then(function(resources) { - resources["js"].should.have.lengthOf(1); + resources.js.should.have.lengthOf(1); }); }); - it('should extend books plugins', function() { + it("should extend books plugins", function() { var resources = book.plugins.resources("website"); - resources["js"].should.have.lengthOf(1); + resources.js.should.have.lengthOf(1); }); }); - describe('eBook', function() { - it('should return a valid list of resources', function() { + describe("eBook", function() { + it("should return a valid list of resources", function() { return plugin.getResources("ebook") .then(function(resources) { - resources["css"].should.have.lengthOf(1); + resources.css.should.have.lengthOf(1); }); }); - it('should extend books plugins', function() { + it("should extend books plugins", function() { var resources = book.plugins.resources("ebook"); // There is resources from highlight plugin and this plugin - resources["css"].should.have.lengthOf(2); - should.exist(_.find(resources["css"], { - path: './resources/test' + resources.css.should.have.lengthOf(2); + should.exist(_.find(resources.css, { + path: "./resources/test" })); }); }); }); - describe('Filters', function() { + describe("Filters", function() { var plugin; before(function() { @@ -110,11 +109,11 @@ describe('Plugins', function () { return book.plugins.load(plugin); }); - it('should valid a plugin', function() { + it("should valid a plugin", function() { should(plugin.isValid()).be.exactly(true); }); - it('should return a map of filters', function() { + it("should return a map of filters", function() { var filters = plugin.getFilters(); _.size(filters).should.equal(2); @@ -122,22 +121,22 @@ describe('Plugins', function () { filters.should.have.property("helloCtx"); }); - it('should correctly extend template filters', function() { - return book.template.renderString('{{ "World"|hello }}') + it("should correctly extend template filters", function() { + return book.template.renderString("{{ \"World\"|hello }}") .then(function(content) { content.should.equal("Hello World"); }); }); - it('should correctly set book as context', function() { - return book.template.renderString('{{ "root"|helloCtx }}') + it("should correctly set book as context", function() { + return book.template.renderString("{{ \"root\"|helloCtx }}") .then(function(content) { content.should.equal("root:"+book.root); }); }); }); - describe('Blocks', function() { + describe("Blocks", function() { var plugin; before(function() { @@ -149,22 +148,22 @@ describe('Plugins', function () { var testTpl = function(str, args, options) { return book.template.renderString(str, args, options) - .then(book.template.postProcess) + .then(book.template.postProcess); }; - it('should valid a plugin', function() { + it("should valid a plugin", function() { should(plugin.isValid()).be.exactly(true); }); - it('should correctly extend template blocks', function() { - return testTpl('{% test %}hello{% endtest %}') + it("should correctly extend template blocks", function() { + return testTpl("{% test %}hello{% endtest %}") .then(function(content) { content.should.equal("testhellotest"); }); }); - it('should correctly accept shortcuts', function() { - return testTpl('$$hello$$', {}, { + it("should correctly accept shortcuts", function() { + return testTpl("$$hello$$", {}, { type: "markdown" }) .then(function(content) { @@ -172,43 +171,50 @@ describe('Plugins', function () { }); }); - it('should correctly extend template blocks with defined end', function() { - return testTpl('{% test2 %}hello{% endtest2end %}') + it("should correctly extend template blocks with defined end", function() { + return testTpl("{% test2 %}hello{% endtest2end %}") .then(function(content) { content.should.equal("test2hellotest2"); }); }); - it('should correctly extend template blocks with sub-blocks', function() { - return testTpl('{% test3join separator=";" %}hello{% also %}world{% endtest3join %}') + it("should correctly extend template blocks with sub-blocks", function() { + return testTpl("{% test3join separator=\";\" %}hello{% also %}world{% endtest3join %}") .then(function(content) { content.should.equal("hello;world"); }); }); - it('should correctly extend template blocks with different sub-blocks', function() { - return testTpl('{% test4join separator=";" %}hello{% also %}the{% finally %}world{% endtest4join %}') + it("should correctly extend template blocks with different sub-blocks", function() { + return testTpl("{% test4join separator=\";\" %}hello{% also %}the{% finally %}world{% endtest4join %}") .then(function(content) { content.should.equal("hello;the;world"); }); }); - it('should correctly extend template blocks with arguments', function() { - return testTpl('{% test5args "a", "b", "c" %}{% endtest5args %}') + it("should correctly extend template blocks with arguments", function() { + return testTpl("{% test5args 'a', 'b', 'c' %}{% endtest5args %}") .then(function(content) { content.should.equal("test5a,b,ctest5"); }); }); - it('should correctly extend template blocks with args and kwargs', function() { - return testTpl('{% test5kwargs "a", "b", "c", d="test", e="test2" %}{% endtest5kwargs %}') + it("should correctly extend template blocks with args and kwargs", function() { + return testTpl("{% test5kwargs 'a', 'b', 'c', d='test', e='test2' %}{% endtest5kwargs %}") .then(function(content) { content.should.equal("test5a,b,c,d:test,e:test2,__keywords:truetest5"); }); }); + + it("should correctly extend template blocks with access to context", function() { + return testTpl("{% set name = 'john' %}{% test6context %}{% endtest6context %}", {}) + .then(function(content) { + content.should.equal("test6johntest6"); + }); + }); }); - describe('Blocks without parsing', function() { + describe("Blocks without parsing", function() { var plugin; before(function() { @@ -222,21 +228,21 @@ describe('Plugins', function () { var filetype = parsers.get(markup); return book.template.renderString(str, args, options) - .then(filetype.page).get('sections').get(0).get('content') - .then(book.template.postProcess) + .then(filetype.page).get("sections").get(0).get("content") + .then(book.template.postProcess); }; - it('should correctly process unparsable for markdown', function() { - return testTpl('.md', '{% test %}**hello**{% endtest %}') + it("should correctly process unparsable for markdown", function() { + return testTpl(".md", "{% test %}**hello**{% endtest %}") .then(function(content) { content.should.equal("<p>test**hello**test</p>\n"); }); }); - it('should correctly process unparsable for asciidoc', function() { - return testTpl('.adoc', '{% test %}**hello**{% endtest %}') + it("should correctly process unparsable for asciidoc", function() { + return testTpl(".adoc", "{% test %}**hello**{% endtest %}") .then(function(content) { - content.should.equal('<div class="paragraph">\n<p>test**hello**test</p>\n</div>'); + content.should.equal("<div class=\"paragraph\">\n<p>test**hello**test</p>\n</div>"); }); }); }); diff --git a/test/plugins/blocks/index.js b/test/plugins/blocks/index.js index 0848238..9bdbe86 100644 --- a/test/plugins/blocks/index.js +++ b/test/plugins/blocks/index.js @@ -39,18 +39,23 @@ module.exports = { }, "test5args": { process: function(blk) { - return "test5"+blk.args.join(',')+"test5"; + return "test5"+blk.args.join(",")+"test5"; } }, "test5kwargs": { process: function(blk) { - var s = blk.args.join(','); + var s = blk.args.join(","); for (var key in blk.kwargs) { - s = s + ','+key+':'+blk.kwargs[key]; + s = s + ","+key+":"+blk.kwargs[key]; } return "test5"+s+"test5"; } }, + "test6context": { + process: function() { + return "test6"+(this.ctx.name)+"test6"; + } + }, } };
\ No newline at end of file diff --git a/test/plugins/replace_highlight/index.js b/test/plugins/replace_highlight/index.js index 25f9642..2e8f71d 100644 --- a/test/plugins/replace_highlight/index.js +++ b/test/plugins/replace_highlight/index.js @@ -2,7 +2,7 @@ module.exports = { blocks: { "code": { process: function(blk) { - var lang = blk.kwargs.language || 'code'; + var lang = blk.kwargs.language || "code"; return lang+"_"+blk.body+"_"+lang; } diff --git a/test/resolve.js b/test/resolve.js index b31a10d..e474ed0 100644 --- a/test/resolve.js +++ b/test/resolve.js @@ -1,7 +1,6 @@ -var fs = require('fs'); -var path = require('path'); +var path = require("path"); -describe('Resolve Files', function () { +describe("Resolve Files", function () { var book; before(function() { @@ -11,50 +10,50 @@ describe('Resolve Files', function () { }); }); - describe('book.fileIsInBook', function() { - it('should return true for correct paths', function() { - book.fileIsInBook(path.join(book.root, 'README.md')).should.equal(true); - book.fileIsInBook(path.join(book.root, 'styles/website.css')).should.equal(true); + describe("book.fileIsInBook", function() { + it("should return true for correct paths", function() { + book.fileIsInBook(path.join(book.root, "README.md")).should.equal(true); + book.fileIsInBook(path.join(book.root, "styles/website.css")).should.equal(true); }); - it('should return true for root folder', function() { - book.fileIsInBook(path.join(book.root, './')).should.equal(true); + it("should return true for root folder", function() { + book.fileIsInBook(path.join(book.root, "./")).should.equal(true); book.fileIsInBook(book.root).should.equal(true); }); - it('should return false for files out of scope', function() { - book.fileIsInBook(path.join(book.root, '../')).should.equal(false); - book.fileIsInBook('README.md').should.equal(false); - book.fileIsInBook(path.resolve(book.root, '../README.md')).should.equal(false); + it("should return false for files out of scope", function() { + book.fileIsInBook(path.join(book.root, "../")).should.equal(false); + book.fileIsInBook("README.md").should.equal(false); + book.fileIsInBook(path.resolve(book.root, "../README.md")).should.equal(false); }); - it('should correctly handle windows paths', function() { - book.fileIsInBook(path.join(book.root, '\\styles\\website.css')).should.equal(true); + it("should correctly handle windows paths", function() { + book.fileIsInBook(path.join(book.root, "\\styles\\website.css")).should.equal(true); }); }); - describe('book.resolve', function() { - it('should resolve a file to its absolute path', function() { - book.resolve('README.md').should.equal(path.resolve(book.root, 'README.md')); - book.resolve('website/README.md').should.equal(path.resolve(book.root, 'website/README.md')); + describe("book.resolve", function() { + it("should resolve a file to its absolute path", function() { + book.resolve("README.md").should.equal(path.resolve(book.root, "README.md")); + book.resolve("website/README.md").should.equal(path.resolve(book.root, "website/README.md")); }); - it('should correctly handle windows paths', function() { - book.resolve('styles\\website.css').should.equal(path.resolve(book.root, 'styles\\website.css')); + it("should correctly handle windows paths", function() { + book.resolve("styles\\website.css").should.equal(path.resolve(book.root, "styles\\website.css")); }); - it('should correctly resolve all arguments', function() { - book.resolve('test', 'hello', '..', 'README.md').should.equal(path.resolve(book.root, 'test/README.md')); + it("should correctly resolve all arguments", function() { + book.resolve("test", "hello", "..", "README.md").should.equal(path.resolve(book.root, "test/README.md")); }); - it('should correctly resolve to root folder', function() { - book.resolve('test', '/README.md').should.equal(path.resolve(book.root, 'README.md')); - book.resolve('test', '\\README.md').should.equal(path.resolve(book.root, 'README.md')); + it("should correctly resolve to root folder", function() { + book.resolve("test", "/README.md").should.equal(path.resolve(book.root, "README.md")); + book.resolve("test", "\\README.md").should.equal(path.resolve(book.root, "README.md")); }); - it('should throw an error for file out of book', function() { + it("should throw an error for file out of book", function() { (function() { - return book.resolve('../README.md'); + return book.resolve("../README.md"); }).should.throw(); }); }); diff --git a/test/summary.js b/test/summary.js index 9c6df00..2d3a248 100644 --- a/test/summary.js +++ b/test/summary.js @@ -1,8 +1,8 @@ -var fs = require('fs'); -var path = require('path'); +var fs = require("fs"); +var path = require("path"); -describe('Summary', function () { - describe('Parsing', function() { +describe("Summary", function () { + describe("Parsing", function() { var book; before(function() { @@ -12,13 +12,13 @@ describe('Summary', function () { }); }); - it('should correctly list items', function() { + it("should correctly list items", function() { book.should.have.property("summary"); book.summary.should.have.property("chapters"); book.summary.chapters.should.have.lengthOf(4); }); - it('should correctly mark non-existant entries', function() { + it("should correctly mark non-existant entries", function() { book.summary.chapters[0].exists.should.have.equal(true); book.summary.chapters[1].exists.should.have.equal(true); book.summary.chapters[2].exists.should.have.equal(true); @@ -26,7 +26,7 @@ describe('Summary', function () { }); }); - describe('Generation', function() { + describe("Generation", function() { var book; before(function() { @@ -36,30 +36,30 @@ describe('Summary', function () { }); }); - it('should create files according to summary', function() { + it("should create files according to summary", function() { book.should.have.file("index.html"); book.should.have.file("PAGE1.html"); book.should.have.file("folder/PAGE2.html"); }); - it('should correctly output summary', function() { + it("should correctly output summary", function() { var PAGE = fs.readFileSync( path.join(book.options.output, "index.html"), { encoding: "utf-8" } ); PAGE.should.be.html({ - ".book-summary .chapter[data-level='0'] a": { + ".book-summary .chapter[data-level=\"0\"] a": { attributes: { href: "./index.html" } }, - ".book-summary .chapter[data-level='1'] a": { + ".book-summary .chapter[data-level=\"1\"] a": { attributes: { href: "./PAGE1.html" } }, - ".book-summary .chapter[data-level='2'] a": { + ".book-summary .chapter[data-level=\"2\"] a": { attributes: { href: "./folder/PAGE2.html" } diff --git a/test/templating.js b/test/templating.js index af29d25..f92154b 100644 --- a/test/templating.js +++ b/test/templating.js @@ -1,6 +1,6 @@ var pkg = require("../package.json"); -describe('Templating', function () { +describe("Templating", function () { var book; before(function() { @@ -12,19 +12,19 @@ describe('Templating', function () { var testTpl = function(str, args, options) { return book.template.renderString(str, args, options) - .then(book.template.postProcess) + .then(book.template.postProcess); }; - describe('Context', function() { - it('should correctly have access to generator', function() { - return testTpl('{{ gitbook.generator }}') + describe("Context", function() { + it("should correctly have access to generator", function() { + return testTpl("{{ gitbook.generator }}") .then(function(content) { content.should.equal("website"); }); }); - it('should correctly have access to gitbook version', function() { - return testTpl('{{ gitbook.version }}') + it("should correctly have access to gitbook version", function() { + return testTpl("{{ gitbook.version }}") .then(function(content) { content.should.equal(pkg.version.toString()); }); diff --git a/test/website.js b/test/website.js index 91340a0..ebbd18c 100644 --- a/test/website.js +++ b/test/website.js @@ -1,8 +1,5 @@ -var fs = require('fs'); -var path = require('path'); - -describe('Website generator', function () { - describe('Basic Book', function() { +describe("Website generator", function () { + describe("Basic Book", function() { var book; before(function() { @@ -12,11 +9,11 @@ describe('Website generator', function () { }); }); - it('should correctly output an index.html', function() { + it("should correctly output an index.html", function() { book.should.have.file("index.html"); }); - it('should correctly copy assets', function() { + it("should correctly copy assets", function() { book.should.have.file("gitbook"); book.should.have.file("gitbook/app.js"); book.should.have.file("gitbook/style.css"); |